Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct Fields Not Updating When Another Object Tells Struct to Update

Tags:

struct

go

I have the following struct that has a function that can update its fields:

type Dog struct {
    name string
    age  int
}

func (dog *Dog) growOld() {    
    dog.name = "old dog"
    dog.age++
}

The above works fine on its own. However, when the struct belongs to another object and said object tells the struct to update its fields, the changes seem to occur but do not get applied:

package main

import (
    "fmt"
)

type Owner struct {
    dog Dog
}

func newOwner(dog Dog) Owner {
    var owner Owner
    owner.dog = dog

    return owner
}

func (owner Owner) tellDogToGrowOld() {
    owner.dog.growOld()
}

func main() {
    var dog Dog
    dog.name = "dog"

    owner := newOwner(dog)
    owner.tellDogToGrowOld()       

    fmt.Println(dog) // dog's name is still `dog` and age is 0.
}

I assume I have to use pointers somehow but can't quite figure out how.

like image 564
Floating Sunfish Avatar asked Sep 01 '25 16:09

Floating Sunfish


2 Answers

The type of a method's receiver should be a pointer type if you want that method to modify the receiver's state.

That is, the same way as you've declared the growOld method, the tellDogToGrowOld method should also have a pointer reciever:

func (owner *Owner) tellDogToGrowOld() {
    owner.dog.growOld()
}

Alternatively, you could make the field that you want to modify to be a pointer, e.g.:

type Owner struct {
    dog *Dog
}

func newOwner(dog *Dog) Owner {
    var owner Owner
    owner.dog = dog

    return owner
}

func (owner Owner) tellDogToGrowOld() {
    owner.dog.growOld()
}
like image 179
mkopriva Avatar answered Sep 04 '25 15:09

mkopriva


Set the field in the Owner to be a *Dog not a Dog

type Owner struct {
    dog *Dog
}

func newOwner(dog *Dog) Owner {
    var owner Owner
    owner.dog = dog

    return owner
}

when calling from main use &dog

var dog Dog
    dog.name = "dog"

    owner := newOwner(&dog)

https://play.golang.org/p/LpFqW09dOs4

like image 23
Vorsprung Avatar answered Sep 04 '25 15:09

Vorsprung