更改具有指针接收器的非结构体的值

huangapple go评论71阅读模式
英文:

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

问题

如果我有一个不是结构体的类型,我如何使用指针接收器来改变它的值?

例如,给定以下代码:

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)
}

它的输出是:

64
64

为什么它不输出以下内容:

64
32

英文:

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

?

答案1

得分: 3

你正在更改指针i的值,而不是指针所指向的值。

通过使用*运算符,您可以看到预期的输出:

*i = newValue

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

英文:

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

答案2

得分: 0

对于你的函数定义:

func (i *MyInt) Change() {
    newValue := MyInt(32)
    i = &newValue
}

当你调用这个函数:

myInt := MyInt(64)
myInt.Change()

myInt 的值将传递给 i,所以在调用 func (i *MyInt) Change() 后,你只修改了 i,而没有修改 myInt

英文:

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.

huangapple
  • 本文由 发表于 2016年12月27日 03:00:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/41335255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定