英文:
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
答案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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论