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

lf2*_*215 21 struct pointers interface go

如果我有:

   type foo struct{
   }

   func bar(baz interface{}) {
   }
Run Code Online (Sandbox Code Playgroud)

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

ANi*_*sus 48

要打开*foo到一个interface{}很简单:

f := &foo{}
bar(f) // every type implements interface{}. Nothing special required
Run Code Online (Sandbox Code Playgroud)

为了回到a *foo,你可以做一个类型断言:

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

    // f is of type *foo
}
Run Code Online (Sandbox Code Playgroud)

类型开关(类似,但如果baz可以是多种类型,则很有用):

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

  • @JuandeParras:如果你不知道`baz`可能是什么类型,那么你将不得不使用反射(`import'反映"`).这就像`encoding/json`这样的包可以在不事先知道的情况下基本上编码任何类型. (5认同)

小智 6

使用反射

reflect.ValueOf(myStruct).Interface().(newType)
Run Code Online (Sandbox Code Playgroud)

  • `reflect` 可以做到这一点,但这是一种繁重且危险的转换方式。有一种更简单的方法,在接受的答案中进行了描述。 (4认同)