create a range with a start and end in go

In Go, we can create a range using the built-in range keyword.

To create a range with a start and end value, we can use a for loop in combination with the range keyword along with the make function to create a slice of a specified length.

Here is an example of creating a range with a start and end value:

main.go
start := 1
end := 10

// create a slice of length (end - start + 1)
numbers := make([]int, end-start+1)

for i := range numbers {
    numbers[i] = start + i
}

fmt.Println(numbers) // [1 2 3 4 5 6 7 8 9 10]
207 chars
12 lines

In this example, we create a range of numbers from 1 to 10 by setting the start and end values. We create a slice by using the make function with a length of end - start + 1. We then iterate over the slice using a range loop and set the value of each element in the slice using the formula start + i. Finally, we print the numbers slice to the console which outputs [1 2 3 4 5 6 7 8 9 10].

Note: The range keyword can also be used to iterate over maps, channels, and strings in Go.

gistlibby LogSnag