英文:
Assign a new value to a struct field
问题
我有一个关于结构字段的问题。
我创建了一个名为Point
的类,其中有一个方法Move()
,它通过dx
增加或减少对象变量x
的值。另一个方法Print()
用于输出结果。
在main()
函数中,我创建了一个新的实例,其中x
的默认值为3,dx
的默认值为2,然后我调用了Move()
和Print()
方法。我期望在Move()
方法中x
的值会改变,并且Print()
方法会输出Final x=5
,但实际上它显示的是:
2014/07/28 15:49:44 New X=5
2014/07/28 15:49:44 Final X=3
我的代码有什么问题?
type Point struct {
x, dx int
}
func (s Point) Move() {
s.x += s.dx
log.Printf("New X=%d", s.x)
}
func (s Point) Print() {
log.Printf("Final X=%d", s.x)
}
func main() {
st := Point{ 3, 2 }
st.Move()
st.Print()
}
英文:
I have a problem with structure fields.
I've created a class Point
with one method Move()
that increases or decreases object variable x
by dx
. Another method Print
is used to output results.
In main()
a new instance is created with default x = 3
and dx = 2
, then I call Move()
and Print()
. I expect that value of x
is changed during Move()
and Print()
will produce Final x=5
, but instead of it displays this:
2014/07/28 15:49:44 New X=5
2014/07/28 15:49:44 Final X=3
What's wrong with my code?
<!-- language: lang-golang -->
type Point struct {
x, dx int
}
func (s Point) Move() {
s.x += s.dx
log.Printf("New X=%d", s.x)
}
func (s Point) Print() {
log.Printf("Final X=%d", s.x)
}
func main() {
st := Point{ 3, 2 };
st.Move()
st.Print()
}
答案1
得分: 9
你需要在这里使用指针接收器,否则每次只会更改原始对象的副本。在Go语言中,所有东西都是按值传递的。
type Point struct {
x, dx int
}
func (s *Point) Move() {
s.x += s.dx
log.Printf("New X=%d", s.x)
}
func (s *Point) Print() {
log.Printf("Final X=%d", s.x)
}
func main() {
st := Point{ 3, 2 };
st.Move()
st.Print()
}
英文:
You need to use a pointer receiver here or you are only changing a copy of the original object every time. Everything is passed by value in go.
type Point struct {
x, dx int
}
func (s *Point) Move() {
s.x += s.dx
log.Printf("New X=%d", s.x)
}
func (s *Point) Print() {
log.Printf("Final X=%d", s.x)
}
func main() {
st := Point{ 3, 2 };
st.Move()
st.Print()
}
答案2
得分: 1
这是指针接收器和值接收器之间的区别。
这是指针接收器和值接收器之间的区别。
http://golang.org/doc/faq#methods_on_values_or_pointers
英文:
That's the difference between pointer receiver and value receiver
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论