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)
}

单个返回值能够不使用括号ui

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
相关文章
相关标签/搜索