如何将数据从函数/方法中保存到go struct中



我只是从GO开始,我很难将数据保存在struct中。来自其他语言,我了解到GO中没有class。出于类似的目的,可以使用struct,并且可以将功能"添加"到结构中。所以我写了以下简单程序:

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?
}

您从评论中可以看到,我对实例化my_struct中的self.the_number中未保存的结果感到困惑。

所以我发现我可以通过做

来解决这个问题
my_struct.the_number = my_struct.add(2)

但是我的方法/函数有时可能会变得复杂,其中我想从函数内部将大量数据保存到my_struct

能比我更聪明的灵魂给我一个关于我在这里缺少的东西的提示吗?

如何从函数内部将数据保存到实例化的struct

您应该在struct方法func (self *MyStruct) add(another_number int) int中使用指针,因为没有*变量(self)是按值传递的,而不是通过引用。例如。您正在更新原始对象的副本,并丢弃此更改。

这是一个基本的东西,在Go之旅中涵盖了众多的东西 - 每个人都应该在开始编码之前接受它。

另一个选项是从该方法返回self - 它将遵循"不可变"样式,因此您可以编写代码: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?
}

最新更新