This question already has an answer here:
- How to set and get fields in struct's method 3 answers
- Assign a new value to Golang structure field 2 answers
- Struct field reverts [duplicate] 1 answer
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>