[英]Instantiate a new obj using Go reflect and type assert to an interface
I can't explain why the following is working.我无法解释为什么以下内容有效。
package main
import (
"fmt"
"reflect"
"strings"
)
type MyInterface interface {
someFunc()
}
type Dock struct {
}
func (d *Dock) someFunc() {
}
type Group struct {
Docks []Dock `better:"sometag"`
}
func foo(model interface{}) {
v1 := reflect.Indirect(reflect.ValueOf(model))
for i := 0; i < v1.NumField(); i++ {
tag := v1.Type().Field(i).Tag.Get("better")
if strings.HasPrefix(tag, "sometag") {
inter := v1.Field(i).Interface()
typ := reflect.TypeOf(inter).Elem()
fmt.Println("Type:", typ.String())
// Want to instantiate type like &Dock{} then assign it to some interface,
// but using reflect
n := reflect.New(typ)
_, ok := n.Interface().(MyInterface)
fmt.Println("Why is it OK?", ok)
}
}
}
func main() {
g := &Group{}
foo(g)
/*var v1, v2 interface{}
d1 := &Dock{}
v1 = d1
_, ok1 := v1.(MyInterface)
d2 := Dock{}
v2 = d2
_, ok2 := v2.(MyInterface)
fmt.Println(ok1, ok2)*/
}
It prints它打印
Type: main.Dock
OK? true
If it's a Dock type, then it's not a pointer to Dock.如果它是一个 Dock 类型,那么它就不是一个指向 Dock 的指针。 Why does it conforms to
MyInterface
?为什么它符合
MyInterface
?
https://play.golang.org/p/Z9mR8amYOM7 https://play.golang.org/p/Z9mR8amYOM7
Where as the d2 example in the comment does not.评论中的 d2 示例没有。
In go
doc for reflect.New
在
go
文档中reflect.New
。新
New returns a Value representing a pointer to a new zero value for the specified type.
New 返回一个 Value,表示指向指定类型的新零值的指针。 That is, the returned Value's Type is PtrTo(typ).
也就是说,返回的 Value 的 Type 是 PtrTo(typ)。
n := reflect.New(typ)
fmt.Println("Type:", n.String())
It will print Type: <*main.Dock Value>
means n
is a pointer of Dock
.You miss the part using reflect.New
return the pointer.它将打印
Type: <*main.Dock Value>
表示n
是Dock
的指针。你错过了使用反射的部分reflect.New
返回指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.