使用全局范围初始化struct,其中type依赖于布尔值

时间:2018-05-26 19:11:11

标签: go struct types scope

我最近开始使用Golang并偶然发现了一个问题:

我有两个结构humanalien,它们都基于creature结构。我想根据if语句中isAlien布尔值的值初始化其中一个。

使用human := human{}表示法或if块中的外来等价物进行初始化,不能从if语句外部访问实例。

另一方面,在if语句之前声明变量的类型和名称以及在if语句中初始化变量的常用解决方案并不起作用,因为有两种不同的类型: / p>

var h human //use human or alien here?
if isAlien {
  h = alien{} //Error: incompatible types
} else {
 h = human{}
}
//same when swapping human with alien at the declaration

我知道我可以在if语句之前声明这两种类型,但这种解决方案对我来说似乎并不优雅。

我有什么明显的解决方案吗?

2 个答案:

答案 0 :(得分:1)

正如您所指出的,这个陈述清楚地表明了问题:

var h human //use human or alien here?

如果您计划在创建对象后使用该h变量,那么h的类型必须是可以接受humanalien的价值。

在Go中执行此操作的方法是使用ìnterfacealien都可以实现的human

所以你应该声明一个类似的界面:

type subject interface {
    // you should list all functions that you plan to use on "h" afterwards
    // both "human" and "alien" must implement those functions 
}

然后:

var h subject

会做的伎俩。

答案 1 :(得分:0)

所以,我要走出去,说你可能会错误地思考这个问题。

我看到你的例子时遇到的第一个问题是:这个函数的返回类型是什么?换句话说,您需要 h的签名是什么?如果alien具有嵌入式结构creature(这似乎是您尝试遵循的继承模式),并且在声明{{1}后从函数返回human成为h,任何消耗你的功能的东西只会知道它正在处理creature,所以没有必要将它声明为creature或者首先是human

怀疑你真正想做的就是离开这里的具体结构,而不是使用接口。在那个世界中,您拥有alien界面,creaturehuman都会满足alien界面。您不一定知道您在下游处理哪一个,但您能够可靠地调用creature方法,并且相应的creaturehuman实施将是调用。