Go error: non-constant array bound

Go

Go Problem Overview


I'm trying to calculate the necessary length for an array in a merge sort implementation I'm writing in go. It looks like this:

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

I then get this complaint when running go test:

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

I assume go does not enjoy users instantiating an Array's length with a calculated value. It only accepts constants. Should I just give up and use a slice instead? I expect a slice is a dynamic array meaning it's either a linked list or copies into a larger array when it gets full.

Go Solutions


Solution 1 - Go

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBreedlyView Question on Stackoverflow
Solution 1 - GoevanmcdonnalView Answer on Stackoverflow