Golang : Populate slice with sequential integers example
Helping out a friend here, putting the code example down here for future references. Basically, he needs to generate a slice with sequential integers such as [1,2,3,4,5]
and also need to generate slice that have negative numbers such as [2,1,0,-1,-2,-3,-4,-5]
.
The code that follows is self-explanatory. Here you go!
package main
import (
"fmt"
)
func sequentialInt(start, end int) []int {
var size int
// check if end > start
if end > start {
size = end - start
size = size + 1 // because counting starts from 0
intSlice := make([]int, size)
for i := 0; i < len(intSlice); i++ {
intSlice[i] = start + i
}
return intSlice
} else {
size = start - end
size = size + 1 // plus 1 because counting starts from 0
intSlice := make([]int, size)
for i := 0; i < len(intSlice); i++ {
intSlice[i] = start - i
}
return intSlice
}
}
func main() {
numbers := sequentialInt(0, 10)
fmt.Println(numbers)
numbers2 := sequentialInt(-10, 5)
fmt.Println(numbers2)
// test for reverse order
numbers3 := sequentialInt(9, -11)
fmt.Println(numbers3)
}
Output:
[0 1 2 3 4 5 6 7 8 9 10]
[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5]
[9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11]
Happy coding!
References:
https://www.socketloop.com/tutorials/golang-generate-random-integer-or-float-number
See also : Golang : Generate random string
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.8k Golang : Experimenting with the Rejang script
+34.7k Golang : Upload and download file to/from AWS S3
+16.1k Golang : Check if a string contains multiple sub-strings in []string?
+10.8k Golang : Create S3 bucket with official aws-sdk-go package
+9.7k Golang : Translate language with language package example
+23.9k Golang : How to validate URL the right way
+13.5k Golang : Gin framework accept query string by post request example
+4.8k Swift : Convert (cast) Float to Int or Int32 value
+9.1k Golang : How to get ECDSA curve and parameters data?
+6.3k Golang : How to determine if request or crawl is from Google robots
+16.5k Golang : Get own process identifier
+12.3k Golang : Arithmetic operation with numerical slices or arrays example