Go – How do you change the value of a pointer parameter?

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

Go - How do you change the value of a pointer parameter?

问题

在Golang中,可以将指针参数的值更改为其他值吗?

例如,

  1. func main() {
  2. i := 1
  3. test(&i)
  4. }
  5. func test(ptr interface{}) {
  6. v := reflect.ValueOf(ptr)
  7. fmt.Println(v.CanSet()) // false
  8. v.SetInt(2) // panic
  9. }

链接:https://play.golang.org/p/3OwGYrb-W-

是否可以让test()i指向另一个值2?

英文:

In Golang, is it possible to change a pointer parameter's value to something else?

For example,

  1. func main() {
  2. i := 1
  3. test(&i)
  4. }
  5. func test(ptr interface{}) {
  6. v := reflect.ValueOf(ptr)
  7. fmt.Println(v.CanSet()) // false
  8. v.SetInt(2) // panic
  9. }

https://play.golang.org/p/3OwGYrb-W-

Is it possible to have test() change i to point to another value 2?

答案1

得分: 12

不确定这是否是你要找的内容,但是是的,你可以将指针的值更改为其他值。下面的代码将打印出2和3:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. i := 1
  7. testAsAny(&i)
  8. fmt.Println(i)
  9. testAsInt(&i)
  10. fmt.Println(i)
  11. }
  12. func testAsAny(ptr interface{}) {
  13. *ptr.(*int) = 2
  14. }
  15. func testAsInt(i *int) {
  16. *i = 3
  17. }
英文:

Not sure if this is what you were looking for,
but yes you can change a pointer's value to something else.
The code below will print 2 and 3:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. i := 1
  7. testAsAny(&i)
  8. fmt.Println(i)
  9. testAsInt(&i)
  10. fmt.Println(i)
  11. }
  12. func testAsAny(ptr interface{}) {
  13. *ptr.(*int) = 2
  14. }
  15. func testAsInt(i *int) {
  16. *i = 3
  17. }

答案2

得分: 2

以下是使用反射包设置值的方法。关键点是设置指针的元素,而不是指针本身。

  1. func test(ptr interface{}) {
  2. v := reflect.ValueOf(ptr).Elem()
  3. v.SetInt(2)
  4. }

playground示例

请注意,在这个特定的示例中,不需要使用反射包,可以使用另一种方法实现。

英文:

Here's now to set the value using the reflect package. The key point is to set the pointer's element, not the pointer itself.

  1. func test(ptr interface{}) {
  2. v := reflect.ValueOf(ptr).Elem()
  3. v.SetInt(2)
  4. }

playground example

Note that the reflect package is not needed for this specific example as shown in another answer.

huangapple
  • 本文由 发表于 2017年5月13日 07:53:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/43947891.html
匿名

发表评论

匿名网友

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

确定