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条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改