为Golang结构域指定一个新值 [英] Assign a new value to Golang structure field
问题描述
我用一个方法创建了一个类 Point
code> Move(),通过 dx
增加或减少对象变量 x
。 打印
用于输出结果。
x = 3
和 dx = 2
创建一个新实例,然后我调用 Move()
和 Print()
。我期望 x
的值在 Move()
和 Print() code>会产生 Final x = 5
,但不是显示这个:
2014/07/28 15:49:44新X = 5
2014/07/28 15:49:44最终X = 3
我的代码出了什么问题?
类型Point结构{
x,dx int
}
func(s Point)Move(){
sx + = s.dx
log.Printf( 新X =%d,SX)
}
FUNC(多个点)打印(){
log.Printf(最终X =% d,sx)
}
func main(){
st:= Point {3,2};
st.Move()
st.Print()
}
解决方案您需要在这里使用指针,或者每次只更改原始对象的副本。一切都按值传递中去了。
< pre
$ b $ + = s.dx
log.Printf(New X =%d,sx)
}
func(s * Point)Print(){
log.Printf(Final X =%d,sx)
}
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?
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 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屋!