go 流程控制和函数

go语言基础之流程控制和函数

流程控制

  • 简单的if else语句
      if a > 10 {  
          # do something
        } else {
          # do something
        }
    
  • switch 语句
      switch a {
          // 多条件匹配,且默认每个case 都自带break!
          case a,c,b,d:
               # do something
          case b:
               # do something
               // fallthrough的特点是强制执行之后的所有case,
               // 无论case的结果是否为Ture
               fallthrough
          default:
               # do something
      }
    
  • select 语句
      select {
          case communication clause :
             statement(s);      
          case communication clause :
             statement(s); 
          /* 你可以定义任意数量的 case */
          default : /* 可选 */
             statement(s);
      }
      每个 case 都必须是一个通信
      所有 channel 表达式都会被求值
      所有被发送的表达式都会被求值
      如果任意某个通信可以进行,它就执行,其他被忽略。
      如果有多个 case 都可以运行,Select 会随机公平地选出一个执行。其他不会执行。 
      否则:
          如果有 default 子句,则执行该语句。
          如果没有 default 子句,select 将阻塞,直到某个通信可以运行;Go 不会重新对 channel 或值进行求值。
    
  • break 语句
      break 主要功能是结束整个循环!
              for true {
                      if condition{
                          break;
                      }
              }
      当condition 为true时结束整个循环
    
  • continue 语句
      continue 跳过循环!
              for true{
                      if condition{
                          continue;
                      }
              }
    
  • goto 语句
      goto 有点像汇编语言中的语法,也是go比较特色的控制语句!
             /* 循环 */
             LOOP: for a < 20 {
                if a == 15 {
                   /* 跳过迭代 */
                   a = a + 1
                   goto LOOP
                }
                fmt.Printf("a的值为 : %d\n", a)
                a++     
             }  
    

    函数

  • 函数定义
      func function_name( [parameter list] ) [return_types] {
         函数体
      }
    
  • 值传递和引用传递
      值传递:
      值传递是指在调用函数时将实际参数复制一份传递到函数中,  
      这样在函数中如果对参数进行修改,将不会影响到实际参数。
      int a:= 10
      def change(x int)
          x := 1;
      change(a)
      a的值不会改变
        
      引用传递:
      引用传递是指在调用函数时将实际参数的地址传递到函数中,
      那么在函数中对参数所进行的修改,将影响到实际参数。
      int a:= 10
      func change(x *int)
          &x := 1;
      change(a)
      a的值改变为1
    
  • 函数回调
    如何实现函数回调
      // 声明一个函数类型
      type newType func(int) int 
        
      func callBack(a int) int {
      }
        
      func testRun(a int , f newType){
          f(a)
      }
      func main(){
          testRun(1,callBack)
      }
    
  • 函数方法
      type My struct{
          high int
          name string
      }
        
      func (m My) showName() string{
          return m.name
      }
    

    总结

    学习了这么多语言,go还是蛮有意思的哦~

Life is more than the present.