golang:将struct指针转换为interface {}

时间:2014-06-26 05:12:03

标签: pointers struct interface go

如果我有:

   type foo struct{
   }

   func bar(baz interface{}) {
   }

以上是一成不变的 - 我无法改变foo或bar。另外,baz必须转换回bar内的foo结构指针。如何将& foo {}转换为接口{},以便在调用bar时将其用作参数?

3 个答案:

答案 0 :(得分:44)

*foo变成interface{}是微不足道的:

f := &foo{}
bar(f) // every type implements interface{}. Nothing special required

要返回*foo,您可以执行 type assertion

func bar(baz interface{}) {
    f, ok := baz.(*foo)
    if !ok {
        // baz was not of type *foo. The assertion failed
    }

    // f is of type *foo
}

type switch (类似,但如果baz可以是多种类型,则非常有用):

func bar(baz interface{}) {
    switch f := baz.(type) {
    case *foo: // f is of type *foo
    default: // f is some other type
    }
}

答案 1 :(得分:2)

使用反射

b

答案 2 :(得分:0)

不完全相关,但是我用Google搜索问题“将接口结构转换为指针”并到达此处。

因此,请注意:将interface of T转换为interface of *T

//
// Return a pointer to the supplied struct via interface{}
//
func to_struct_ptr(obj interface{}) interface{} {
    vp := reflect.New(reflect.TypeOf(obj))
    vp.Elem().Set(reflect.ValueOf(obj))
    return vp.Interface()
}