Avatar ·

指针与值:何时在Go的参数和返回值中使用*和&?

我刚开始学习Go,总是搞不清楚什么时候传指针,什么时候传值。虽然读了很多文章,但实践中还是做不对。 例如,我有一个User结构体和一个更新它的函数: ```go type User struct { Name string Age int Score float64 } func UpdateScore(u User, newScore float64) { u.Score = newScore } ``` 当我调用`UpdateScore(myUser, 95.5)`时,调用后`myUser.Score`保持不变。我明白了这是因为Go复制了结构体。于是我改成`*User`: ```go func UpdateScore(u *User, newScore float64) { u.Score = newScore } ``` 现在可以了。但是当我写一个返回新用户的函数时,我看到了两种方式: ```go func NewUser(name string, age int) User { ... } func NewUserPtr(name string, age int) *User { ... } ``` 哪一种正确?还有,对于大型结构体怎么办?到处都用指针吗?那基本类型呢?