设为首页 加入收藏

TOP

函数
2019-05-24 14:08:00 】 浏览:76
Tags:函数
  • 声明

    func funcName(input1 type1, input2 type2) (output1 type1, output2 type2) {
      //逻辑代码
      //支持返回多个值
      return value1, value2
    }
    
    //多个返回值
    func SumAndProduct(A, B int) (int, int) {
      return A+B, A*B//直接返回了两个参数
    }
    
    //也可以命名返回参数的变量,然后返回的时候不用带上变量名,因为直接在函数里面初始化了。
    func SumAndProduct(A, B int) (add int, Multiplied int) {
      add = A+B
      Multiplied = A*B
      return//返回的时候不用带上变量名,直接在函数里面初始化了
    }
  • 变参

    接受变参的函数是有着不定数量的参数的。定义函数使其接受变参:

    func myfunc(arg ...int) {}
    //arg ...int告诉Go这个函数接受不定数量的参数**。
    //注意,这些参数的类型全部是int。
    //在函数体中,变量arg是一个int的slice
  • defer延迟语句

    在defer后指定的函数会在函数退出前调用。你可以在函数中添加多个defer语句。当函数执行到最后时,这些defer语句会按照逆序执行,最后该函数返回。

    for i := 0; i < 5; i++ {
      defer fmt.Printf("%d ", i)
    }
    //defer是采用后进先出模式,所以会输出4 3 2 1 0
  • 函数作为值、类型

    • 在Go中函数也是一种变量,我们可以通过type来定义它,它的类型就是所有拥有相同的参数,相同的返回值的一种类型

    • type typeName func(input1 inputType1 , input2 inputType2 [, ...]) (result1 resultType1 [, ...])
    • 函数作为类型到底有什么好处呢?那就是可以把这个类型的函数当做值来传递

      type testInt func(int) bool // 声明了一个函数类型
      
      func isOdd(integer int) bool {
        if integer%2 == 0 {
          return false
        }
        return true
      }
      
      // 声明的函数类型在这个地方当做了一个参数
      func filter(slice []int, f testInt) []int {
        var result []int
        for _, value := range slice {
          if f(value) {
            result = append(result, value)
          }
        }
      
        return result
      }
      
      func main(){
        slice := []int {1, 2, 3, 4, 5, 7}
          odd := filter(slice, isOdd)    // isodd函数当做值来传递了
          fmt.Println("Odd elements of slice are: ", odd)
      }
      
      //函数当做值和类型在我们写一些通用接口的时候非常有用,
      //通过上面例子我们看到testInt这个类型是一个函数类型
      //我们可以实现很多种的逻辑,这样使得我们的程序变得非常的灵活。

参考书籍:https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/preface.md

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇go标准库I/O模型:epoll+多协程 下一篇struct,interface,method

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目