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