如何将任何值设置为interface{}

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

How to set any value to interface{}

问题

我有以下代码:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Point struct {
  6. x,y int
  7. }
  8. func decode(value interface{}) {
  9. fmt.Println(value) // -> &{0,0}
  10. // 这是一个简化的例子,实际上可以是任何类型的值,而不仅仅是Point类型的值。
  11. value = &Point{10,10}
  12. }
  13. func main() {
  14. var p = new(Point)
  15. decode(p)
  16. fmt.Printf("x=%d, y=%d", p.x, p.y) // -> x=0, y=0,期望结果是x=10, y=10
  17. }

我想将任何类型的值设置为传递给decode函数的值。在Go中是否可能,或者我理解错了什么?

http://play.golang.org/p/AjZHW54vEa

英文:

I have following code:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Point struct {
  6. x,y int
  7. }
  8. func decode(value interface{}) {
  9. fmt.Println(value) // -> &{0,0}
  10. // This is simplified example, instead of value of Point type, there
  11. // can be value of any type.
  12. value = &Point{10,10}
  13. }
  14. func main() {
  15. var p = new(Point)
  16. decode(p)
  17. fmt.Printf("x=%d, y=%d", p.x, p.y) // -> x=0, y=0, expected x=10, y=10
  18. }

I want to set value of any type to the value passed to decode function. Is it possible in Go, or I misunderstand something?

http://play.golang.org/p/AjZHW54vEa

答案1

得分: 5

通用地,只能使用反射:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type Point struct {
  7. x, y int
  8. }
  9. func decode(value interface{}) {
  10. v := reflect.ValueOf(value)
  11. for v.Kind() == reflect.Ptr {
  12. v = v.Elem()
  13. }
  14. n := reflect.ValueOf(Point{10, 10})
  15. v.Set(n)
  16. }
  17. func main() {
  18. var p = new(Point)
  19. decode(p)
  20. fmt.Printf("x=%d, y=%d", p.x, p.y)
  21. }
英文:

Generically, only using reflection:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type Point struct {
  7. x, y int
  8. }
  9. func decode(value interface{}) {
  10. v := reflect.ValueOf(value)
  11. for v.Kind() == reflect.Ptr {
  12. v = v.Elem()
  13. }
  14. n := reflect.ValueOf(Point{10, 10})
  15. v.Set(n)
  16. }
  17. func main() {
  18. var p = new(Point)
  19. decode(p)
  20. fmt.Printf("x=%d, y=%d", p.x, p.y)
  21. }

答案2

得分: 1

我不确定你的确切目标。

如果你想要断言value是一个指向Point的指针并对其进行更改,你可以这样做:

  1. func decode(value interface{}) {
  2. p := value.(*Point)
  3. p.x = 10
  4. p.y = 10
  5. }
英文:

I'm not sure of your exact goal.

If you want to assert that value is a pointer to Point and change it, you can do that :

  1. func decode(value interface{}) {
  2. p := value.(*Point)
  3. p.x=10
  4. p.y=10
  5. }

huangapple
  • 本文由 发表于 2012年9月18日 22:14:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/12478779.html
匿名

发表评论

匿名网友

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

确定