在go中设置传递给函数的接口值 [英] Set the interface value passed to the function in go

查看:131
本文介绍了在go中设置传递给函数的接口值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想改变

Get(title string )(out interface{})

类似:

Get(title string,out interface{})

这样我就可以通过引用传递接口,并让该方法像这样为我填充它:

So that I can passing the interface by reference and let the method fill it for me like :

var i CustomInterface
Get("title" , CustomInterface)
i.SomeOperationWithoutTypeAssertion() //the i is nil here(my problem)

func Get(title string,typ interface{}){
     ...
     typ=new(ATypeWhichImplementsTheUnderlyingInterface)
}

,但i.SomeOperationWithoutTypeAssertion()不起作用,因为调用Get("title" , CustomInterface)

but the i.SomeOperationWithoutTypeAssertion() doesn't work because the i is nil after calling the Get("title" , CustomInterface)

推荐答案

Go没有像C ++这样的语言中存在的透明引用参数的概念,因此您无法提出以下要求:您的Get函数接收接口变量的副本,因此不会在调用范围内更新变量.

Go doesn't have the concept of transparent reference arguments as found in languages like C++, so what you are asking is not possible: Your Get function receives a copy of the interface variable, so won't be updating variable in the calling scope.

如果您确实希望函数能够更新作为参数传递的内容,则必须将其作为指针传递(即称为Get("title", &i)).没有语法可以指定参数应该是指向任意类型的指针,但是所有指针都可以存储在interface{}中,以便可以将类型用作参数.然后,您可以使用类型声明/ reflect确定您得到的是哪种类型.您需要依靠运行时错误或紧急情况来捕获参数的错误类型.

If you do want a function to be able to update something passed as an argument, then it must be passed as a pointer (i.e. called as Get("title", &i)). There is no syntax to specify that an argument should be a pointer to an arbitrary type, but all pointers can be stored in an interface{} so that type can be used for the argument. You can then use a type assertion / switch or the reflect package to determine what sort of type you've been given. You'll need to rely on a runtime error or panic to catch bad types for the argument.

例如:

func Get(title string, out interface{}) {
    ...
    switch p := out.(type) {
    case *int:
        *p = 42
    case *string:
        *p = "Hello world"
    ...
    default:
        panic("Unexpected type")
    }
}

这篇关于在go中设置传递给函数的接口值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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