Reputation: 1287
If I have a type which is not a struct how do I change its value with a pointer receiver?
For example, given the following code:
package main
import (
"fmt"
)
type MyInt int
func (i *MyInt) Change() {
newValue := MyInt(32)
i = &newValue
}
func main() {
myInt := MyInt(64)
fmt.Println(myInt)
myInt.Change()
fmt.Println(myInt)
}
It outputs:
64
64
Why does it not output the following:
64
32
?
Upvotes: 0
Views: 150
Reputation: 10254
for your function define:
func (i *MyInt) Change() {
newValue := MyInt(32)
i = &newValue
}
when you call this function:
myInt := MyInt(64)
myInt.Change()
the value of myInt
will pass to i
, so after call func (i *MyInt) Change()
, you only modify the i
, not myInt
.
Upvotes: 0
Reputation:
You're changing the value of the pointer i
, not the value at which the pointer is pointing.
You will see your expected output by using the *
operator:
*i = newValue
https://play.golang.org/p/mKsKC0lsj9
Upvotes: 3