Go 语言使用函数 - Go语言中文社区

Go 语言使用函数


定义函数

func test(a int, b int, c string) (int, string, bool) {
    return a + b, c, true
}

func main() {
    v1, s1, _ := test(10, 20, "hello")
    fmt.Println("v1:", v1, ", s1:", s1)
}

或者

func test(a, b int, c string) (res int, str string, bl bool) {
    res = a + b
    str = c
    bl = true
    return
}

func main() {
    v1, s1, _ := test(10, 20, "hello")
    fmt.Println("v1:", v1, ", s1:", s1)
}

单个返回值可以不使用括号

func test() int {
    return 10
}

指针内存逃逸

func main() {
    res := testPtr()
    fmt.Println("city:", *res)
}

// 返回一个string类型的指针
func testPtr() *string {
    // name 不会逃逸
    name := "张三"
    ptrn := &name
    fmt.Println("*ptrn:", *ptrn)
    
    // city 会逃逸,因为需要在函数外使用
    city := "广州"
    ptrc := &city
    return ptrc
}
# 编译查看堆栈详情
go build -o test.exe --gcflags "-m -m -l" test.go
版权声明:本文来源Segmentfault,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://segmentfault.com/a/1190000039972014
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-13 19:53:04
  • 阅读 ( 811 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢