douhui9631 2018-09-21 18:56
浏览 412
已采纳

在golang中包含整数和nil值的数组?

I am new to golang. But I couldn't find an answer to this.

In python I can do,

array = [1, 2, 3, None, 5]

But in go when I write

var array = [5]int {1, 2, 3, nil, 5}

The compiler gives me the following error:

cannot convert nil to type int

How can I create an array in golang which is a mix of integer and nil values?

  • 写回答

2条回答 默认 最新

  • drwo32555 2018-09-21 20:15
    关注

    First a bit of theory. Python is a dynamically typed language. While each individual value has a type, your variables can be assigned values of any type without a problem. As a consequence, python collections can contain multiple types of values and don't complain. The following is a valid python tuple (1, 'a', None, True). Go is a statically typed language. If your variable is defined as an integer you cannot assign any non-integer value to it. As a consequence, collections in Go have a type and can only contain a single type of object.

    Now to practice. There are a few ways to do what you want. The classical C way would be to pick an integer value you are never going to encounter and use that as a null value. A 0 or a -1 or something. This is not very robust though.

    A more idiomatic way is to define your own type.

    package main
    
    import "fmt"
    
    type NilInt struct {
        value int
        null  bool
    }
    
    func (n *NilInt) Value() interface{} {
        if n.null {
            return nil
        }
        return n.value
    }
    
    func NewInt(x int) NilInt {
        return NilInt{x, false}
    }
    
    func NewNil() NilInt {
        return NilInt{0, true}
    }
    
    func main() {
        var x = []NilInt{NewNil(), NewInt(10), NewNil(), NewInt(5)}
        for _, i := range x {
            fmt.Printf("%v ", i.Value())
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题