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

rockdean · · 4832 次点击
如果方法里有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
<a href="/user/dasenlin12" title="@dasenlin12">@dasenlin12</a> 明白了,<a href="/user/JY115" title="@JY115">@JY115</a> 彻明白了。
#3