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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程