golang的指针在struct中的应用区别

rockdean · · 4832 次点击
正解!带指针是传递该结构体的地址,里面对结构体参数做修改会相应修改结构体自身的值
#5
更多评论
如果方法里有this.username='aaa',就有区别了
#1
``` package main import ( "fmt" "strconv" ) type User struct { username string password string age int32 } func (this User) Set() { this.username = "set name" } func (this *User) Set2() { this.username = "set name" } func main() { user := &User{username: "a", password: "aaa", age: 25} user.Set() fmt.Println("user:", user) user2 := &User{username: "a", password: "aaa", age: 25} user2.Set2() fmt.Println("user2:", user2) } ``` 运行结果 ``` user: username:a password:aaa age:25 user2: username:set name password:aaa age:25 ``` 可见,带指针的struct函数可修改struct实例,而不带指针的函数只是对实例的拷贝进行操作
#2