从golang中的特定接口获取基础类型

从golang中的特定接口获取基础类型,go,reflection,Go,Reflection,作为示例,我可以从接口工作中获得其底层类型的零值吗 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(&copy) fm :=v.Elem() modified :

作为示例,我可以从接口工作中获得其底层类型的零值吗

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(&copy)
    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()
}

由于
w
包含指向
工作者的指针,因此您可能希望获取它所指向的元素的零值。获取元素后,可以创建其类型的零值:

v := reflect.ValueOf(w).Elem() // Get the element pointed to
zero := reflect.Zero(v.Type()) // Create the zero value
如果您传入一个指向
MakeSomething
的非指针,上述代码段将死机。要防止出现这种情况,您可能需要执行以下操作:

v := reflect.ValueOf(w)
if reflect.TypeOf(w).Kind() == reflect.Ptr {
    v = v.Elem()
}
zero := reflect.Zero(v.Type())

如果你真的想有一个指向一个新的
工作者的指针
,你只需将
reflect.Zero(v.Type())
替换为
reflect.new(v.Type())

我的第一个问题,非常感谢~我发现了区别,
fmt.Println(reflect.ValueOf(w.Type())/print*main.Testg
fmt.printlin(reflect.ValueOf(&w).Type()//print*main.Worker
如果我使用第二种方法(我认为这可以将w点的值更改为)@linvan不客气!是的,
&w
真的很没用。它将为您提供一个指向接口的指针,该接口包含一个指向该值的指针。而且你很少(从来没有,真的)在Go中使用指向接口的指针。