All arguments–including the receiver–is a copy inside the function/method. You can only modify the copy.
This applies to pointers too: the receiver value (the fi
pointer) is a copy, so you can't modify the original pointer, only the copy.
Usually the receiver is a non-nil
pointer, and you modify the pointed value–which results in the original pointed value changed.
In your case you either have to return the pointer and assign the return value:
func (fi *FooInt) FromString(i string) *FooInt {
num, _ := strconv.Atoi(i)
tmp := FooInt(num)
return &tmp
}
func main() {
var fi *FooInt
fi = fi.FromString("5")
fmt.Printf("%v %v\n", fi, *fi)
}
This will output (try it on the Go Playground):
0xc0000b4020 5
Or pass a non-nil
pointer to what you want to change, in your case it would be of type **FooInt
func (fi *FooInt) FromString(i string, p **FooInt) {
num, _ := strconv.Atoi(i)
tmp := FooInt(num)
*p = &tmp
}
func main() {
var fi *FooInt
fi.FromString("5", &fi)
fmt.Printf("%v %v\n", fi, *fi)
}
This outputs the same. Try it on the Go Playground.
But easiest would be to just ensure the receiver is not nil
, so the pointed value can simply be modified:
func (fi *FooInt) FromString(i string) {
num, _ := strconv.Atoi(i)
*fi = FooInt(num)
}
func main() {
var fi *FooInt
fi = new(FooInt)
fi.FromString("5")
fmt.Printf("%v %v\n", fi, *fi)
}
Output is the same. Try this one on the Go Playground.