给 Golang 结构体字段赋值 [英] Assign a new value to Golang structure field
问题描述
结构字段有问题.
我创建了一个 Point
类,使用一个方法 Move()
通过 dx<增加或减少对象变量
x
/代码>.另一种方法Print
用于输出结果.
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.
在main()
中创建一个新实例,默认x = 3
和dx = 2
,然后我调用Move()
和 Print()
.我希望 x
的值在 Move()
和 Print()
期间改变将产生 Final x=5
, 而不是显示这个:
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
我的代码有什么问题?
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()
}
推荐答案
此处需要使用指针,否则每次都只更改原始对象的副本.一切都是在 go 中按值传递.
You need to use a pointer 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()
}
这篇关于给 Golang 结构体字段赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!