Skip to content

Latest commit

 

History

History
executable file
·
99 lines (87 loc) · 1.59 KB

File metadata and controls

executable file
·
99 lines (87 loc) · 1.59 KB

控制结构

switch 结构

Go 中的 switch-case 结构和 C++ 中的选择结构并不相同。

i := 1
switch i {
    case 0: func1()
    case 1: func2()
    // ...
    default:
        funcd()
}

而 C++ 代码停止 switch 操作需要手动 break。

    i = 1
    switch(i) {
        case 1: func1(); break;
        case 2: func2(); break;
        //...
        default:funcd();
    }

Go 中将这种特性去除,如果确实需要在执行完 case 的情况下还要继续执行,可以在后面添加关键字 fallthrough。如 Go代码:

	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++ 代码:

    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 语句

  • 基于计数器的迭代
for i := 0; i < 5; i++ {
    
}
for i, j := 0, N; i < j; i,j = i+a, j-1 {
    
}
  • 基于判断的循环
for i < 6 {
    
}
  • 无限循环
for {

}
  • for-range 结构
for i := range x {

}