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

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

How to set any value to interface{}

问题

我有以下代码:

package main

import (
   "fmt"
)

type Point struct {
    x,y int
}

func decode(value interface{}) {
    fmt.Println(value) // -> &{0,0}

    // 这是一个简化的例子,实际上可以是任何类型的值,而不仅仅是Point类型的值。
    value = &Point{10,10}
}

func main() {
    var p = new(Point)
    decode(p)

    fmt.Printf("x=%d, y=%d", p.x, p.y) // -> x=0, y=0,期望结果是x=10, y=10
}

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

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

英文:

I have following code:

package main

import (
   "fmt"
)

type Point struct {
    x,y int
}

func decode(value interface{}) {
    fmt.Println(value) // -> &{0,0}

    // This is simplified example, instead of value of Point type, there
    // can be value of any type.
    value = &Point{10,10}
}

func main() {
    var p = new(Point)
    decode(p)

    fmt.Printf("x=%d, y=%d", p.x, p.y) // -> x=0, y=0, expected x=10, y=10
}

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

通用地,只能使用反射:

package main

import (
	"fmt"
	"reflect"
)

type Point struct {
	x, y int
}

func decode(value interface{}) {
	v := reflect.ValueOf(value)
	for v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	n := reflect.ValueOf(Point{10, 10})
	v.Set(n)
}

func main() {
	var p = new(Point)
	decode(p)
	fmt.Printf("x=%d, y=%d", p.x, p.y)
}
英文:

Generically, only using reflection:

package main

import (
	"fmt"
	"reflect"
)

type Point struct {
	x, y int
}

func decode(value interface{}) {
	v := reflect.ValueOf(value)
	for v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	n := reflect.ValueOf(Point{10, 10})
	v.Set(n)
}

func main() {
	var p = new(Point)
	decode(p)
	fmt.Printf("x=%d, y=%d", p.x, p.y)
}

答案2

得分: 1

我不确定你的确切目标。

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

func decode(value interface{}) {
    p := value.(*Point)
    p.x = 10
    p.y = 10
}
英文:

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 :

func decode(value interface{}) {
	p := value.(*Point)
    p.x=10
    p.y=10
}

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:

确定