为Golang结构域指定一个新值 [英] Assign a new value to Golang structure field

查看:110
本文介绍了为Golang结构域指定一个新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我用一个方法创建了一个类 Point

code> Move(),通过 dx 增加或减少对象变量 x 打印用于输出结果。

c $ c>用默认的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆