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

rockdean · · 4806 次点击
<a href="/user/dasenlin12" title="@dasenlin12">@dasenlin12</a> 明白了,<a href="/user/JY115" title="@JY115">@JY115</a> 彻明白了。
#3
更多评论
如果方法里有this.username=&#39;aaa&#39;,就有区别了
#1
``` package main import ( &#34;fmt&#34; &#34;strconv&#34; ) type User struct { username string password string age int32 } func (this User) Set() { this.username = &#34;set name&#34; } func (this *User) Set2() { this.username = &#34;set name&#34; } func main() { user := &amp;User{username: &#34;a&#34;, password: &#34;aaa&#34;, age: 25} user.Set() fmt.Println(&#34;user:&#34;, user) user2 := &amp;User{username: &#34;a&#34;, password: &#34;aaa&#34;, age: 25} user2.Set2() fmt.Println(&#34;user2:&#34;, user2) } ``` 运行结果 ``` user: username:a password:aaa age:25 user2: username:set name password:aaa age:25 ``` 可见,带指针的struct函数可修改struct实例,而不带指针的函数只是对实例的拷贝进行操作
#2