Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize golang slice with int numbers from 0 to N

I am almost certain that I read about a simple "tricky" way to initialize slice of ints with the numbers from 0 to N, but I cannot find it anymore.

What is the simplest way to do this?

like image 583
gsf Avatar asked Jun 06 '16 17:06

gsf


1 Answers

You just use make passing N for the length then use a simple for loop to set the values...

mySlice := make([]int, N)
for i := 0; i < N; i++ {
      mySlice[i] = i
}

Here's a full example on play; https://play.golang.org/p/yvyzuWxN1M

like image 120
evanmcdonnal Avatar answered Oct 02 '22 01:10

evanmcdonnal