This question already has an answer here:
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>
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?
}