مرکزی مواد پر جائیں
eLearner.app
ماڈیول 6 · سبق 3 از 5کورس میں 28/50~10 min
ماڈیول اسباق (3/5)

ٹائپ سوئچ

A type switch discriminates among multiple possible types of an interface value. It's the generalization of comma ok when there are more than one case.

Syntax

Go
func describe(i interface{}) string {
    switch v := i.(type) {
    case int:
        return fmt.Sprintf("int %d", v)
    case string:
        return fmt.Sprintf("string %q", v)
    case nil:
        return "nil"
    default:
        return fmt.Sprintf("altro tipo: %T", v)
    }
}
  • i.(type) is a special syntax, valid ONLY inside switch.
  • v := ... binds the value with the current case's type: inside case int, v has type int.
  • default catches all other types; there v has the type of the original interface.
  • case nil matches the interface with a nil dynamic type.

"Nameless" case

If you don't need the typed value, you can omit the v:

Go
switch i.(type) {
case int:
    // you know it's an int, but you don't have a variable of that type
case string:
    // ...
}

A form used when you just need to discriminate the type, not operate on the value.

Multiple types in the same case

Go
switch v := i.(type) {
case int, int64:
    // here v is still interface{}: the "common" type is just the interface
    fmt.Println("numero intero:", v)
case string:
    // here v is string
    fmt.Println("stringa:", v)
}

Typical use case: formatted printing

Go
func print(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("%d\n", v)
    case string:
        fmt.Printf("%s\n", v)
    case fmt.Stringer:
        fmt.Println(v.String())
    default:
        fmt.Printf("%v\n", v)
    }
}

fmt.Println itself uses a type switch internally to handle the standard formats.

Type switch vs reflection

For a few known types → type switch (fast, readable). For dynamic inspection of unknown types → the reflect package (more powerful but slower and more verbose).

Try it

ورزش#go.m6.l3.e1
کوششیں: 0لوڈ ہو رہا ہے…

Implement describe(i interface{}) string that returns 'int', 'string' or 'altro' depending on the dynamic type.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Syntax: `switch i.(type) { case T: ... default: ... }`.

3 کوششوں کے بعد حل دستیاب ہے۔

ورزش#go.m6.l3.e2
کوششیں: 0لوڈ ہو رہا ہے…

Write printVal(i interface{}) that uses v := i.(type) and prints with %d for int, %s for string.

ایڈیٹر لوڈ ہو رہا ہے…
اشارہ دکھائیں۔

Inside `case int`, v has type int (you can pass it to Printf).

3 کوششوں کے بعد حل دستیاب ہے۔

Quiz#go.m6.l3.e3
تیار

Which syntax starts a type switch?

Go
switch ??? {
  case int: ...
}
جواب کے اختیارات

Recap

  • switch v := i.(type) { case T: ... }: discriminates on the dynamic type.
  • Inside a single-type case, v has the case's type.
  • case T1, T2: v keeps the original interface's type.
  • default for unhandled cases; case nil for the nil interface.
  • No fallthrough in type switches.
  • 1 type → type assertion; 2+ types → type switch.