I want to know how two separate struct methods can modify a field in third struct.
What I'm getting now is {[20]} {[30]}
Like the two methods on B and C should modify the list field of A and the output should be in the same slice
Package main
import "fmt"
type A struct{
list []intint
}
type B struct{
a A
}
type C struct{
a A
}
func (r *B) update(n int){
r.a.list = append(r.a.list, n)
}
func (r *C) update(n int){
r.a.list = append(r.a.list, n)
}
func main(){
b := B{}
c := C{}
b.update(20)
c.update(30)
fmt.Println(b)
fmt.Println(c)
/* if i do;
a := A{}
fmt.Println(a.list)
I want to have {[20, 30}
*/
}
You have an instance of B
and C
which have 2 different instance of A
(as their fields) and thus you have 2 different slices. Why should appending an element to one be observed in the other? They are independent on different areas of the memory.
If you want updating one be observed on the other, you actually want 1 instance of A
, accessed from 2 different places.
So create one instance of A
and store pointers to it in instances of B
and C
. So modify B
and C
to have a pointer field:
type B struct {
a *A
}
type C struct {
a *A
}
Testing the complete app:
type A struct {
list []int
}
type B struct {
a *A
}
type C struct {
a *A
}
func (r *B) update(n int) {
r.a.list = append(r.a.list, n)
}
func (r *C) update(n int) {
r.a.list = append(r.a.list, n)
}
func main() {
a := A{}
b := B{a: &a}
c := C{a: &a}
b.update(20)
c.update(30)
fmt.Println(b, b.a)
fmt.Println(c, c.a)
}
Output (try it on the Go Playground):
{0xc00000e018} &{[20 30]}
{0xc00000e018} &{[20 30]}