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

rockdean · · 4862 次点击
更多评论
如果方法里有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