控制结构
switch 结构
Go 中的 switch-case 结构和 C++ 中的选择结构并不相同。
1 2 3 4 5 6 7 8
| i := 1 switch i { case 0: func1() case 1: func2() default: funcd() }
|
而 C++ 代码停止 switch 操作需要手动 break。
1 2 3 4 5 6 7
| i = 1 switch(i) { case 1: func1(); break; case 2: func2(); break; default:funcd(); }
|
Go 中将这种特性去除,如果确实需要在执行完 case 的情况下还要继续执行,可以在后面添加关键字 fallthrough。如 Go代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| k := 6 switch k { case 4: fmt.Println("was <= 4") fallthrough case 5: fmt.Println("was <= 5") fallthrough case 6: fmt.Println("was <= 6") fallthrough case 7: fmt.Println("was <= 7") fallthrough case 8: fmt.Println("was <= 8") fallthrough default: fmt.Println("default case") }
|
C++ 代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| switch(i) { case 4: cout<<"was <= 4"<<endl; case 5: cout<<"was <= 5"<<endl; case 6: cout<<"was <= 6"<<endl; case 7: cout<<"was <= 7"<<endl; case 8: cout<<"was <= 8"<<endl; default: cout<<"default case"<<endl; }
|
Go 里面的这种做法可以直接和 C++ 中去除 break 的做法直接类比
for 语句
1 2 3 4 5 6
| for i := 0; i < 5; i++ { } for i, j := 0, N; i < j; i,j = i+a, j-1 { }
|