> For the complete documentation index, see [llms.txt](https://book.codewithgo.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.codewithgo.com/switch-statement.md).

# 17. Switch

### Switch Statement

When there are multiple branches, `if...else` code can get more verbose. Switch statement provide more efficient way to express multiple branches. Semantic for switch statement is&#x20;

```
switch condition {
    case x: 
        code to execute
    case y:
        code to execute   
    default:
        code to execute     
}
```

When one of the case statement is matched, that code is executed. Default block is executed when there is no matching case.

### No Fall-through

One of the difference switch statement has with other programming languages, is that if one of the case is matched, only that code is executed and switch statement break automatically. This means that cases do not fall-though automatically for switch statement in Go.

{% code title="main.go" %}

```go
i := 2
switch i {
case 1:
	fmt.Println("i is one")
case 2:
	fmt.Println("i is two")
case 3:
	fmt.Println("i is three")
case 4:
	fmt.Println("i is four")
}
```

{% endcode %}

Only `case 2` will be executed.

### Switch without expression

We can also define without any expression and case statement can take care of evaluating condition.

{% code title="main.go" %}

```go
dayOfWeek := 6
switch {
case dayOfWeek == 6 || dayOfWeek == 7:
	fmt.Println("It's weekend!")
case dayOfWeek < 6 && dayOfWeek > 0:
	fmt.Println("It's weekday!")
default:
	fmt.Println("You are not on Earth!")
}
```

{% endcode %}
