英文:
How to change struct variable content?
问题
在上面的示例中,我的例子中变量的改变在方法执行后不会持续。我该如何使用结构体方法来改变结构体变量的值?
英文:
http://play.golang.org/p/wYgfLLQYdm
See example above. In my example the variable change does not last after the method is executed. How can I change a struct variable's value with a struct method?
答案1
得分: 6
你的方法接收器是一个值,而不是一个指针。
这意味着像switch_width_height()
这样的方法是在对象的副本上操作的。
参见:
添加一个*
:
func (s *square) switch_width_height()
然后它将按预期工作:参见play.golang.org。
英文:
Your method receiver is a value, not a pointer.
That means those methods like switch_width_height()
operate on a copy of the object.
See also:
- FAQ "Should I define methods on values or pointers?".
- "Don't Get Bitten by Pointer vs Non-Pointer Method Receivers in Golang"
- "Go 101: Methods on Pointers vs. Values"
- "Go Bootcamp "
Add a '*
':
func (s *square) switch_width_height()
And it will work as expected: see play.golang.org.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论