Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go error: non-constant array bound

Tags:

go

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.

like image 494
Breedly Avatar asked Jul 13 '16 22:07

Breedly


1 Answers

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) 
like image 68
evanmcdonnal Avatar answered Sep 28 '22 05:09

evanmcdonnal