错误: 非常数数组绑定

我试图在 go中编写的合并排序实现中计算数组的必要长度。它看起来像这样:

func merge(array []int, start, middle, end int) {
leftLength := middle - start + 1
rightLength := end - middle
var left [leftLength]int
var right [rightLength]int
//...
}

然后我在运行 go test时收到了这样的投诉:

./mergesort.go:6: non-constant array bound leftLength
./mergesort.go:7: non-constant array bound rightLength

我假设 go不喜欢用户用计算值实例化 Array 的长度。它只接受 常数。我是不是应该放弃,用一片代替?我希望 切片是一个动态数组,这意味着它要么是一个链表,要么是在满了的时候复制到一个更大的数组中。

49438 次浏览

You can't instantiate an array like that with a value calculated at runtime. Instead use make to initialize a slice with the desired length. It would look like this;

left := make([]int, leftLength)