create a range in go

In Go, you can create a range of integers using the range keyword. You can use this range with a for loop to iterate over the range of numbers.

Here's an example of how to create a range of numbers in Go:

main.go
package main

import "fmt"

func main() {
  // Create a range from 1 to 5
  numbers := []int{1, 2, 3, 4, 5}

  // Loop through the range using a for loop
  for _, num := range numbers {
    fmt.Println(num)
  }
}
213 chars
14 lines

In this example, we've created a slice of integers containing the values 1 to 5. We then loop through this slice using a for loop with the range keyword, which returns the index and value of each element in the slice.

The output of this program will be:

main.go
1
2
3
4
5
10 chars
6 lines

You can also create a range of numbers using the make function, like this:

main.go
package main

import "fmt"

func main() {
  // Create a range from 1 to 5
  numbers := make([]int, 5)
  for i := range numbers {
    numbers[i] = i + 1
  }

  // Loop through the range using a for loop
  for _, num := range numbers {
    fmt.Println(num)
  }
}
261 chars
17 lines

In this example, we've created a slice of integers with a length of 5 using the make function. We then fill this slice with the values from 1 to 5 using a for loop with the range keyword.

The output of this program will be the same as the previous example:

main.go
1
2
3
4
5
10 chars
6 lines

related categories

gistlibby LogSnag