Go语言条件判断

条件语句

if条件判断

// if条件判断
if 布尔表达式1 {
    
    
    /*布尔表达式1为true时执行*/
} else if 布尔表达式2 {
    
    
    /*布尔表达式2为true时执行*/
} else {
    
    
    /*以上条件都不满则时执行*/
}

switch条件判断

  1. case支持多条件匹配
  2. 不同的case之间不适用break分割,默认只使用一个case
  3. 使用fallthrough强制执行该条语句下面的所有语句,也可使用break终止
// switch条件判断
switch var1 {
    
    
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}
// type switch
switch x.(type){
    
    
    case type:
       statement(s);      
    case type:
       statement(s); 
    /* 你可以定义任意个数的case */
    default: /* 可选 */
       statement(s);
}
// 使用 fallthrough 会强制执行后面的 case 语句,fallthrough 不会判断下一条 case 的表达式结果是否为 true。
 switch {
    
    
     case false:
     fmt.Println("1、case 条件语句为 false")
     fallthrough
     case true:
     fmt.Println("2、case 条件语句为 true")
     fallthrough
     case false:
     fmt.Println("3、case 条件语句为 false")
     fallthrough
     case true:
     fmt.Println("4、case 条件语句为 true")
     case false:
     fmt.Println("5、case 条件语句为 false")
     fallthrough
     default:
     fmt.Println("6、默认 case")
 }

猜你喜欢

转载自blog.csdn.net/qq_44733706/article/details/113141894