Class 如何从函数/方法在Go结构中保存数据?
我刚开始使用Go,在Class 如何从函数/方法在Go结构中保存数据?,class,go,data-structures,struct,Class,Go,Data Structures,Struct,我刚开始使用Go,在结构中保存数据时遇到了困难。我从其他语言中学到,围棋中没有所谓的类。出于类似目的,可以使用结构,并且可以向结构“添加”函数。因此,我编写了以下简单程序: package main import "fmt" type MyStruct struct { the_number int } func (self MyStruct) add(another_number int) int { self.the_number += another_number /
结构中保存数据时遇到了困难。我从其他语言中学到,围棋中没有所谓的类。出于类似目的,可以使用结构
,并且可以向结构“添加”函数。因此,我编写了以下简单程序:
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?
}
从评论中可以看出,我对结果没有保存在self中感到困惑。实例化的my\u结构中的编号
所以我发现我可以通过
my_struct.the_number = my_struct.add(2)
但是I方法/函数有时会变得复杂,我希望从函数内部将大量数据保存到my_struct
有没有比我更聪明的人能告诉我我错过了什么
如何将数据从函数中保存到实例化的struct
?您应该在struct方法func(self*MyStruct)add(另一个int)int
中使用指针,因为没有*
变量(self)是通过值传递的,而不是通过引用传递的。例如,您正在更新原始对象的副本,而这些更改将被放弃
这是一个基本的东西,并且在中有很好的介绍-每个人都应该在开始编写Go之前使用它
另一个选项是从方法返回self
——它将遵循“不可变”的样式,这样您就可以编写类似这样的代码:my\u struct=my\u struct.add(1).add(2)
不要使用self
;请改用描述性名称。缺少指针。也许从包含所有基本内容的开始,包括你真的必须否决这个问题吗?重复,第20个。@akond:downvote=“这个问题不显示任何研究努力。”第n次问这个问题并不表示研究努力。对否决这个问题的人;你为什么投反对票?这个解决方案似乎效果很好。
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?
}