dounaoji2054 2017-09-06 15:33
浏览 42
已采纳

如何通过函数/方法将数据保存到Go结构中? [重复]

I'm just starting out with Go and I'm having a hard time saving data in a struct. Coming from other languages I learned there is no such thing as a class in Go. For similar purposes, the struct can be used, and functions can be "added" to the struct. So I wrote the following simple program:

package main

import "fmt"

type MyStruct struct {
    the_number int
}
func (self MyStruct) add(another_number int) int {
    self.the_number += another_number  // I save the result to the struct the_number
    return self.the_number
}

func main() {
    my_struct := MyStruct{1}
    result := my_struct.add(2)
    fmt.Println(result)               // prints out 3 as expected
    fmt.Println(my_struct.the_number) // prints out 1. Why not also 3?
}

As you can see from the comments I'm puzzled by the fact that the result is not saved in self.the_number in the instantiated my_struct.

So I found out I can get around this by doing

my_struct.the_number = my_struct.add(2)

But I methods/functions can sometimes become complex in which I want to save a lot of data to the my_struct from within the function.

Could any smarter soul than me give me a tip on what I'm missing here?

How can I save data to an instantiated struct from within a function?

</div>
  • 写回答

1条回答 默认 最新

  • dsrw29618 2017-09-06 15:35
    关注

    You should use pointer in struct method func (self *MyStruct) add(another_number int) int as without the * variable (self) is passed by value, not by references. E.g. you are updating a copy of an original object and this changes are discarded.

    It's a basic stuff and well covered in Tour of Go - everyone should take it before starting coding in Go.

    Another option would be return the self from the method - it would follow "immutable" style so you can write code like: my_struct = my_struct.add(1).add(2)

    package main
    
    import "fmt"
    
    type MyStruct struct {
        the_number int
    }
    func (self *MyStruct) add(another_number int) int {
        self.the_number += another_number
        return self.the_number
    }
    
    func main() {
        my_struct := MyStruct{1}
        result := my_struct.add(2)
        fmt.Println(result)               // prints out 3 as expected
        fmt.Println(my_struct.the_number) // prints out 1. Why not also 3?
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多