go语言基础,三

  • 条件语句

if,if...else中布尔表达式不需要加括号

if 布尔表达式{
    //表达式为真时的执行语句
}
  • switch语句

方式一:

switch vname{
    case v1:
    ...
    break
    case v2:
    ...
    break
    default:
    ...
}

方式二:

switch{
    case 布尔表达式1:
    ...
    break
    case 布尔表达式2:
    ...
    break
    default:
    ...
}

方式三:

fallthrough

使用fallthrough会自动执行下一条case的表达式,不论条件是否为真。

 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")//不执行
    }

select

select 是 Go 中的一个控制结构,类似于用于通信的 switch 语句。每个 case 必须是一个通信操作,要么是发送要么是接收。

select 随机执行一个可运行的 case。如果没有 case 可运行,它将阻塞,直到有 case 可运行。一个默认的子句应该总是可运行的。

select {
    case communication clause  :
       statement(s);      
    case communication clause  :
       statement(s); 
    /* 你可以定义任意数量的 case */
    default : /* 可选 */
       statement(s);
}

select 会循环检测条件,如果有满足则执行并退出,否则一直循环检测。

循环

1.对标C的for(init;condition;post){}

for init;condition;post{
    ....
}

2.对标C的while{}

for condition{}

3.对标C的for{;;}

for{}

4.for each range 循环 进行遍历

str := string[]{"abc","def"}
for i, s := range str {
                fmt.Println(i, s)
        }

函数

  • 函数定义

func functionname ([para1 para1type, para2 para2type...]) [return type]{
    func body
}
  • 函数可以有多个返回值

func swap(x, y string) (string, string) {
   return y, x
}
  • 函数闭包

函数闭包我的理解就是在一个函数内定义了另一个函数,每次调用函数可以返回在该函数内定义的函数。

好处是可以提高代码利用率,有点多态的味道。

func getSequence() func() int {
   i:=0
   return func() int {
      i+=1
     return i  
   }
}