মূল কন্টেন্টে যান
eLearner.app
মডিউল 2 · 4-এর পাঠ 5কোর্সে 9/50~10 min
মডিউল পাঠ (4/5)

ইডিওম্যাটিক সুইচ

Go's switch is more ergonomic than C/Java's: each case has its own implicit block (no break to write), you can group multiple values with a comma, and a switch without an expression behaves like a more readable if/else if chain.

Switch on a value

Go
giorno := "mar"
switch giorno {
case "lun", "mar", "mer", "gio", "ven":
    fmt.Println("feriale")
case "sab", "dom":
    fmt.Println("weekend")
default:
    fmt.Println("sconosciuto")
}

case accepts multiple values separated by commas and there is no implicit fallthrough: as soon as a case is executed, the switch exits.

Switch without a condition

If you omit the expression, the switch evaluates true and each case is a bool condition. It is the idiomatic alternative to long if/else if chains:

Go
switch {
case x < 0:
    fmt.Println("negativo")
case x == 0:
    fmt.Println("zero")
case x < 10:
    fmt.Println("piccolo")
default:
    fmt.Println("grande")
}

Init statement

As with if, switch also accepts an init statement:

Go
switch n := len(s); {
case n == 0:
    fmt.Println("vuoto")
case n > 100:
    fmt.Println("lungo")
default:
    fmt.Println("ok")
}

n exists only inside the switch.

Explicit fallthrough

If you really want execution to fall into the next case, you have to write it:

Go
switch 1 {
case 1:
    fmt.Println("uno")
    fallthrough
case 2:
    fmt.Println("due")  // anche questo viene stampato
case 3:
    fmt.Println("tre")  // questo no
}

Type switch (preview)

It lets you discriminate based on the dynamic type of an interface value. We will cover it in depth in the Interfaces module:

Go
var i interface{} = "ciao"
switch v := i.(type) {
case int:
    fmt.Println("int:", v)
case string:
    fmt.Println("string:", v)
default:
    fmt.Printf("tipo %T\n", v)
}

Try it

ব্যায়াম#go.m2.l4.e1
প্রচেষ্টা: 0লোড হচ্ছে...

Print 'feriale' for lun/mar/mer/gio/ven, 'weekend' otherwise, using a switch on the value of g.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

Group the 5 weekdays into a single case separated by commas.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

ব্যায়াম#go.m2.l4.e2
প্রচেষ্টা: 0লোড হচ্ছে...

Use a switch WITHOUT a condition to print 'neg', 'zero' or 'pos' depending on x.

সম্পাদক লোড হচ্ছে...
ইঙ্গিত দেখান

No expression after `switch`, just `{`.

সমাধান 3 প্রচেষ্টার পরে উপলব্ধ

Quiz#go.m2.l4.e3
প্রস্তুত

What does this program print?

Go
switch 1 {
case 1:
    fmt.Print("a")
case 2:
    fmt.Print("b")
}
উত্তরের বিকল্প

Recap

  • case accepts multiple values separated by commas.
  • No implicit fallthrough: each case has its own implicit break.
  • switch { ... } without an expression = a more readable if/else if chain.
  • Init statement: switch x := f(); { ... }, scope limited to the block.
  • fallthrough exists but is rare; enters the next case WITHOUT evaluating its condition.
  • Type switch v := i.(type) to discriminate based on the dynamic type (Interfaces module).