程序结构

Go学习笔记

条件语句

1、if…else…
  • 条件内可以赋值

  • 条件内赋值的变量作用域就存在于这个if语句里

    if contents, err := ioutil.ReadFile(filename); err == nil {
      fmt.Println(string(contents))
    } else {
      fmt.Println("cannot print file contents: ", err)
    }
    
2、switch
  • switch后可以没有表达式

  • 不需要显示break,switch会自动break,除非使用fallthrough

    func grade(score int) string {
      g := ""
      switch  {
      case score < 0 || score > 100:
          panic(fmt.Sprintf("Wrong score: %d", score))
      case score < 60:
          g = "F"
      case score < 80:
          g = "C"
      case score < 90:
          g = "B"
      case score <= 100:
          g = "A"
      }
      return g
    }
    
3、for
  • 表达式不需要括号

    result := ""
    for ; n > 0; n /= 2 {
      result = strconv.Itoa(n%2) + result
    }
    
  • 表达式可以省略初始条件(相当于while),结束条件,递增条件

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
      fmt.Println(scanner.Text())
    }
    
  • 无线循环

    for {
      fmt.Println("abc")
    }
    
4、函数
  • 返回类型写再最后面
  • 可返回多个值
  • 函数可作为参数
  • 没有默认参数,可选参数
5、指针
  • 不能运算

  • 只有值传递一种方式

6、包/文件
  • 为了支持模块化、封装、单独编译、代码重用
  • 一个名字是大写字母开头,那么该名字是导出的
  • 每个包都是有一个全局唯一的导入路径
Go 

See also