HenryTK
HenryTK

Reputation: 1287

Changing the value of a non-struct with a pointer receiver

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

Answers (2)

BlackMamba
BlackMamba

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

user142162
user142162

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

Related Questions