# 控制语句

## if 判断语句

1. if条件不需使用括号将条件包含起来
2. 大括号{}必须存在，即使只有一行语句
3. 左括号必须在if或else的同一行
4. 在if之后，条件语句之前，可以添加变量初始化语句，使用；进行分隔
5. 在有返回值的函数中，最终的return不能在条件语句中

```go
if num := 10; num < 9 {

} else if num > 11 {

} else {
  
}
```

## switch判断语句

1. switch后跟一个表达式，可以是常量、变量、一个有返回值得函数调用
2. case 后的表达式，如果是常量值，则要求不可重复
3. case后的各个值得数据类型要与switch后的数据类型保持一致
4. case后可以设置多个值，使用逗号分割开来
5. default语句不是必须的，位置也是随意的
6. switch也可以不带表达式，用作if分支
7. switch后的表达式可以直接定义变量，使用分号结束，这点与if相同，但是不推荐
8. case语句后，不需要break语句，默认不回去执行下一个case
9. 如果想要switch穿透，继续判断下个case执行，可以增加 fallthrough关键字

```go
// 值选择
var point = 100
switch point/10 {
  case 10, 9, 8:
  fmt.Println("你很棒")
  case 6, 7:
  fmt.Println("下次继续努力")
  case 5:
  fmt.Println("你不是我亲生的")
  // fallthrough  // 继续执行下一个case
  case 4,3,2,1:
  fmt.Println("你要挨打了")
  default: // default 可以放在任何位置上，不一定放到最后
  fmt.Println("成绩有误")
}
```

## for 循环结构

在go语言中，循环结构只有for循环，没有while循环，支持 break、continue、goto 关键字控制流程。

**普通写法：**

```go
for i := 1; i < 5; i++ {
  fmt.Print("i = " + strconv.FormatInt(int64(i), 10) + " | ")
}
```

**变种写法，类似while，通常用在不确定循环次数的情况：**

```go
j := 1
for j < 5 {
  fmt.Print("j = " + strconv.FormatInt(int64(j), 10) + " | ")
  j++
}
```

**死循环的两种写法：**

```go
for {
	xxxx
}
for ;; {
	xxxx
}
```

**遍历字符串：**

```go
var str = "hello 世界"
for i := 0; i < len(str); i++ {
  fmt.Printf("%c", str[i])
}
// hello ä¸ç 
// 因为汉字的长度不是一个字节，所以这里会有乱码
```

**for range遍历字符串，类似for each：**

```go
var s = "hello 世界"
for i, value := range s {
  fmt.Printf("索引为 %d, 值为%c", str[i])
}
// 结果为 索引为 0, 值为h索引为 1. 入门, 值为e索引为 2, 值为l索引为 3, 值为l索引为 4, 值为o索引为 5, 值为 索引为 6, 值为世索引为 9, 值为界
// for range 针对的是字符进行遍历的
```

**break跳出循环， continue继续循环：**

```go
var sum = 0
for i := 1; i <= 100; i ++ {
  if sum >= 50 {  // 求和值大于五十，停止求和
    break
  }
  if i % 2 == 0 { // 只求和奇数值
    continue
  }
  sum += i
}
```

## goto语句（不建议使用）

```go
fmt.Println("1. 入门")
goto label1
fmt.Println("2")
fmt.Println("3")
label1:
fmt.Println("4")
// 执行结果  1. 入门 4
```


---

# Agent Instructions: 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://yangsx95.gitbook.io/notes/programming-language/golang/kong-zhi-yu-ju.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.
