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

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

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

问题

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

例如,给定以下代码:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type MyInt int
  6. func (i *MyInt) Change() {
  7. newValue := MyInt(32)
  8. i = &newValue
  9. }
  10. func main() {
  11. myInt := MyInt(64)
  12. fmt.Println(myInt)
  13. myInt.Change()
  14. fmt.Println(myInt)
  15. }

它的输出是:

  1. 64
  2. 64

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

  1. 64
  2. 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:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type MyInt int
  6. func (i *MyInt) Change() {
  7. newValue := MyInt(32)
  8. i = &newValue
  9. }
  10. func main() {
  11. myInt := MyInt(64)
  12. fmt.Println(myInt)
  13. myInt.Change()
  14. fmt.Println(myInt)
  15. }

It outputs:

  1. 64
  2. 64

Why does it not output the following:

  1. 64
  2. 32

?

答案1

得分: 3

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

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

  1. *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:

  1. *i = newValue

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

答案2

得分: 0

对于你的函数定义:

  1. func (i *MyInt) Change() {
  2. newValue := MyInt(32)
  3. i = &newValue
  4. }

当你调用这个函数:

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

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

英文:

for your function define:

  1. func (i *MyInt) Change() {
  2. newValue := MyInt(32)
  3. i = &newValue
  4. }

when you call this function:

  1. myInt := MyInt(64)
  2. 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:

确定