dongyi1982 2018-05-26 19:11 采纳率: 0%
浏览 53
已采纳

使用类型取决于布尔值的全局范围初始化结构

I started using Golang recently and stumbled across a problem:

I have two structs, human and alien, which are both based on the creature struct. I want to initialize one of them based on the value of the isAlien boolean inside of an if-statement.

Using the human := human{} notation or the alien equivalent inside the if blocks to initialize, the instances aren't accessible from outside of the if-statement.

On the other hand, the usual solution of declaring the type and the name of the variable before the if-statement and initializing the variable inside the if-statement doesn't work, because there two are different types:

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

I know that I could just declare both types before the if-statement but that solution doesn't seem elegant to me.

Is there some obvious solution that I'm missing here?

  • 写回答

2条回答 默认 最新

  • doujinai2183 2018-05-26 19:26
    关注

    As you noted, the problem is clearly represented by this statement:

    var h human //use human or alien here?
    

    If you plan to use that h variable there after creating the objects, then the type of h must be one that can accept either a human or alien as a value.

    The way to do this in Go is by using an ìnterface that both alien and human can fulfil.

    So you should declare an interface like:

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

    Then:

    var h subject
    

    Will do the trick.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容