将结构指针转换为接口{}

新手上路,请多包涵

如果我有:

    type foo struct{
   }

   func bar(baz interface{}) {
   }

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

原文由 lf215 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 399
2 个回答

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

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

为了回到 *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
}

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

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

原文由 ANisus 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用反映

reflect.ValueOf(myStruct).Interface().(newType)

原文由 archever 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题