Skip to content

Range Between Two Numbers in Golang

The simplest way to range between two numbers in golang is a for loop, in this example, we iterate 5 to 10:

package main

import "fmt"

func main() {
	// numbers between 5 to 10
	for i := 5; i <= 10; i++ {
		fmt.Println(i)
	}
}

There is a small package called iter you can use which is so easy to use:

package main

import (
	"fmt"

	"github.com/thedevsaddam/iter"
)

func main() {
	// numbers between 5 to 10
	for v := range iter.N(5, 11) {
		fmt.Println(v)
	}

	// numbers between 5 to 10, increment by 2
	for v := range iter.N(5, 10, 2) {
		fmt.Println(v)
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *