将结构指针转换为接口{} [英] convert struct pointer to interface{}

查看:74
本文介绍了将结构指针转换为接口{}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

   type foo struct{
   }

   func bar(baz interface{}) {
   }

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

The above are set in stone - I can't change foo or bar. Additionally, baz must converted back to a foo struct pointer inside bar. How do I cast &foo{} to interface{} so I can use it as a parameter when calling bar?

推荐答案

*foo转换为interface{}很简单:

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

为了返回*foo,您可以执行 类型声明 :

In order to get back to a *foo, you can either do a 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
}

类型开关 (类似,但在baz可以是多种类型):

Or a type switch (similar, but useful if baz can be multiple types):

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

这篇关于将结构指针转换为接口{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆