go语言结构体作为函数参数,采用的是值传递

时间:2023-03-10 04:41:35
go语言结构体作为函数参数,采用的是值传递

经过验证,go语言结构体作为函数参数,采用的是值传递。所以对于大型结构体传参,考虑到值传递的性能损耗,最好能采用指针传递。

验证代码:

package main

import (
"fmt"
) type st struct {
id int
name string
} func main() {
d := st{1, "Jo"}
fmt.Println(d, "值传递前")
fValue(d)
fmt.Println(d, "值传递后,外层值不变")
fPoint(&d)
fmt.Println(d, "指针传递后,外层值变化")
} func fValue(s st) {
s.id++
s.name = "of"
fmt.Println(s, "值传递函数")
} func fPoint(s *st) {
s.id++
s.name = "of"
fmt.Println(*s, "指针传递函数")
}

  

结果:

go语言结构体作为函数参数,采用的是值传递