如何创建具有所需类型而不是类型断言的变量 [英] How to create a variable with needed type instead of type assertion

查看:42
本文介绍了如何创建具有所需类型而不是类型断言的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有接口的函数,如下所示:

I have a function which takes an interface, like this:

func method(data interface{})

..因为我需要处理具有共同字段/方法的不同结构.在此功能中,我在不同的地方使用 data 数十次或数百次.一直不愿意添加 switch a.(type){case .. case .. .

.. because I need to process different structs which have common fields/methods. In this function I use data tens or hundreds of times, in different places. It's really unpleasant to add switch a.(type) { case .. case .. all the time.

有没有一种方法可以只用一个带有所需类型的 switch 创建一个变量,然后在以后随处使用此变量?像这样:

Is there a way to create a variable with just one switch with needed type and then just use this variable everywhere later? Something like:

var a .... // something here

switch data.(type) {
case *Struct1:
    a = data.(*Struct1)
case *Struct2:
    a = data.(*Struct2)
}

// Continue with 'a' only
a.Param = 15
fmt.Println(a.String())

推荐答案

Go是一种静态类型的语言,必须在编译时知道 a 的类型.而且由于Go还不支持泛型,因此您无法做自己想做的事.

Go is a statically typed language, the type of a must be known at compile time. And since Go does not support generics yet, you can't do what you want.

尝试提出其他解决方案,例如将要使用 a 进行的操作抽象为一个接口,并让具体类型实现该接口.然后 a 可以是此接口类型的变量,您可以调用它的方法.

Try to come up with some other solution, e.g. abstract away the things you want to do with a into an interface, and have the concrete types implement that interface. Then a can be a variable of this interface type, and you can call methods of it.

如果可以实现,实际上甚至可以将 data 类型的参数更改为该接口,并且不需要类型声明或类型切换.

If you can achieve this, actually you can even change the parameter of the data type to this interface, and no type assertion or type switch is needed.

或者,您可以使用反射来访问由其名称标识的公共字段(用于get或set),但是反射不提供编译时保证,并且通常效率较低.有关如何执行此操作的示例,请参阅以下问题:将接口声明为其类型

Alternatively you could use reflection to access common fields (either for get or set) identified by their name, but reflection provides no compile-time guarantee, and it's usually less efficient. For an example how to do that, see this question: Assert interface to its type

这篇关于如何创建具有所需类型而不是类型断言的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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