在函数传参的时候,见有人用指针传,如下:
type struct Info{
Msg string `json:"msg"`
}
function test(info *Info){
...
return
}
就想着为什么非要传指针呢,你要Info,直接写在函数返回值里不也可在函数间传递吗?
type struct Info{
Msg string `json:"msg"`
}
function test(info Info) Info{
...
return info
}
后来,总结了几点传指针和传值的情况,如下:
一 、传指针
1、要修改变量的值,供函数之后使用,用指针。如
type struct Info{
Msg string `json:"msg"`
}
function test1(info *Info){
...
return
}
function test2(info *Info){
...
return
}
function test(){
info:=&Info{}
test1(info)
test2(info)
fmt.Println(info)
return
}
2、变量是个大的结构,用指针
传值复制大的结构,影响性能