([]构造函数)(nil)

时间:2018-06-06 14:06:59

标签: go slice

我正在阅读中间件链接软件Alice的源代码,并找到了表达式:

func New(constructors ...Constructor) Chain {
    return Chain{append(([]Constructor)(nil), constructors...)}
}

我对代码没有任何问题,除了我之前从未见过表达式([]Slice)(nil)。有没有人有关于这种表达的任何信息?

2 个答案:

答案 0 :(得分:2)

constructors参数复制到新切片中,将其分配给Chain文字中的字段,然后返回新结构。

相当于

func New(constructors ...Constructor) Chain {
    var tmp []Constructor
    tmp = append(tmp, constructors...)
    return Chain{tmp}
}

答案 1 :(得分:2)

这里的爱丽丝的作者,只是随机点击了这个问题。 :)

其他答案解释了append(nil, ...)的作用 - 我在整个库中使用它来复制用户传入的切片。

现在,Go不允许简单地使用append(nil, someElement),因为nil的类型未知。 ([]Constructor)(nil)nil投射到[]Constructor类型以避免这种情况。这是一种类型转换,与int64(123)(*int)(nil)相同。

这是一个最小的例子,由于无类型的nil编译器错误输出:

a := ([]int)(nil)
a = append(a, 1, 2, 3) // works fine, a is of type []int
var b []int
b = append(b, 1, 2, 3) // works fine, b is of type []int
c := nil
c = append(c, 1, 2, 3) // compiler error: the type of c is unknown