> 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 %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://book.codewithgo.com/switch-statement.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
