logo

Programming Languages - Switch

C++ Java Go
fallthrough Yes Yes No

C++

switch(var) {
  case 1:
      do_somthing_1();
      break;
  case 2:
      do_somthing_2();
      break;
  default:
      do_somthing_else();
}

Go

  • Go only runs the selected case, not all the cases that follow (i.e. there is no automatic fall through) but cases can be presented in comma-separated lists.
  • Go's switch cases need not be constants, and the values involved need not be integers.
// With a condition.
switch os := runtime.GOOS; os {
case "darwin":
    fmt.Println("macOS.")
case "linux":
    fmt.Println("Linux.")
default:
    fmt.Printf("%s.\n", os)
}

// Without a condition, the same as `switch true`.
t := time.Now()
switch {
case t.Hour() < 12:
    fmt.Println("Good morning!")
case t.Hour() < 17:
    fmt.Println("Good afternoon.")
default:
    fmt.Println("Good evening.")
}

// Multiple values in one case.
switch db.TransactionStatus() {
case
    db.TransactionStarting,
    db.TransactionActive,
    db.TransactionWaiting,
    db.TransactionCommitted:

    // ...

Type switches:

func do(i interface{}) {
    switch v := i.(type) {
    case int:
        // ...
    case string:
        // ...
    default:
        // ...
    }
}

Rust

Rust uses match keyword for pattern matching, which can be used like switch in other languages.

match var {
    1 => do_somthing_1(),
    2 => do_somthing_2(),
    _ => do_somthing_else(),
}

Java

switch (var) {
  case 1:
      doSomthing1();
      break;
  case 2:
      doSomthing2();
      break;
  default:
      doSomthingElse();;
}

More details: Java switch