【发布时间】:2018-11-05 20:35:20
【问题描述】:
我最近开始使用 Golang,偶然发现了一个问题:
我有两个结构,human 和 alien,它们都基于 creature 结构。我想根据 if 语句中 isAlien 布尔值的值初始化其中一个。
使用 human := human{} 表示法或 if 块内的外来等效符号进行初始化,无法从 if 语句外部访问实例。
另一方面,通常在 if 语句之前声明变量的类型和名称并在 if 语句中初始化变量的解决方案是行不通的,因为有两种不同的类型:
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 语句之前声明这两种类型,但该解决方案对我来说似乎并不优雅。
我在这里缺少一些明显的解决方案吗?
【问题讨论】: