作为一个例子,我能否从接口Work中获取其底层类型的零值?
func MakeSomething(w Worker){
w.Work()
//can I get a zeor value type of The type underlying w?
//I tried as followed, but failed
copy :=w
v := reflect.ValueOf(©)
fm :=v.Elem()
modified :=reflect.Zero(fm.Type())//fm.type is Worker, and modified comes to be nil
fm.Set(modified)
fmt.Println(copy)
}
type Worker interface {
Work()
}
这里是 Go 语言的练习场。
fmt.Println(reflect.ValueOf(w).Type())//输出 *main.Testg
fmt.Println(reflect.ValueOf(&w).Type())//输出 *main.Worker
在我使用第二种方式时(我认为这可以改变指向变量 w 的指针的值) - lin van&w
真的没什么用。它会给你一个指向包含值指针的接口的指针。在 Go 中,你很少(实际上从来不)使用指向接口的指针。 - ANisus