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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度