মূল কন্টেন্টে যান
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.