Using a setter for a struct type does not work as anticipated

Viewed 1429

Using a setter function for a struct, but not working as anticipated:

package main

import "fmt"

type T struct { Val string }

// this setter seems not to work
func (t T) SetVal( s string ) {
        t.Val = s
}

// this setter, using ptr to T, seems to work ok
func (t *T) SetVal2( s string ) {
        (*t).Val = s
}

func main() {
        v := T{"abc"}
        fmt.Println( v )        // prints {abc}
        v.SetVal("pdq")
        fmt.Println( v )        // prints {abc}, was expecting {pdq}!
        v.SetVal2("xyz")
        fmt.Println( v )        // prints {xyz}!
}

I am missing some fundamental understanding - why doesn't SetVal work?

the behavior is similar to setting values in reflect which only works if provided a pointer to the object as versus the object itself

2 Answers

That's the difference between call by value and call by reference. If you are from C++ background , then you would know that it's the same in C++ also. And if you are from java background, then remember all object references are just pointers to the objects really..(meaning to say, when we do Node node = new Node();.. the node is holding the address of the new node object created). Therefore any method on the object(node) is actually called by reference(because node itself is a pointer).. so it reduces back to the same example as above.

Related