gpt4 book ai didi

go - 使用类型取决于 bool 值的全局范围初始化结构

转载 作者:IT王子 更新时间:2023-10-29 02:09:46 34 4
gpt4 key购买 nike

最近开始使用Golang,遇到了一个问题:

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

使用 human := human{} 表示法或 if block 内的外来等效符号进行初始化,无法从 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 语句之前声明这两种类型,但这个解决方案对我来说似乎并不优雅。

我在这里缺少一些明显的解决方案吗?

最佳答案

如您所述,此语句清楚地表明了问题:

var h human //use human or alien here?

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

在 Go 中实现这一点的方法是使用一个 ìnterfacealienhuman 都可以实现。

所以你应该像这样声明一个接口(interface):

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

会成功的。

关于go - 使用类型取决于 bool 值的全局范围初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50546218/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com