From Go 1.22 (expected release February 2024), you will be able to write:

Copyfor i := range 10 {
    fmt.Println(i+1)
}

(ranging over an integer in Go iterates from 0 to one less than that integer).

For versions of Go before 1.22, the idiomatic approach is to write a for loop like this.

Copyfor i := 1; i <= 10; i++ {
    fmt.Println(i)
}
Answer from Paul Hankin on Stack Overflow
🌐
GUI
golangr.com › for
For loops | Learn Go Programming
golang runs the code block only n times. The number of repetitions is called iterations and every round is called an iteration. An array is a set of items of the same data type. You can loop over an array too:
Discussions

loops - Golang code to repeat an html code n times - Stack Overflow
I am working on golang web app. In that I need to iterate an HTML line n number of times. More on stackoverflow.com
🌐 stackoverflow.com
iterating over an integer?
what are the possible uses of this construct? Analysis of the public Go code corpus has revealed that it's by far the most common use case of the 3-clause for loop. More on reddit.com
🌐 r/golang
8
6
December 27, 2023
Beginner question about channels
If you do this package main import "fmt" func main() { queue := make(chan string, 2) queue <- "one" queue <- "two" for elem := range queue { fmt.Println(elem) } close(queue) } Then the for loop never knows to stop (it will stop when the channel it ranges over is closed and it has completed "draining" the channel, but the close channel command is never reached so the loop sits there forever.) package main import ( "fmt" "time" ) func worker(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Println("worker", id, "started job", j) time.Sleep(time.Second) fmt.Println("worker", id, "finished job", j) results <- j * 2 } } func main() { const numJobs = 5 jobs := make(chan int, numJobs) results := make(chan int, numJobs) for w := 1; w <= 3; w++ { go worker(w, jobs, results) } for j := 1; j <= numJobs; j++ { jobs <- j } close(jobs) for a := 1; a <= numJobs; a++ { <-results } } Here the jobs channel close command is reached because the loop immediately before it is limited by the numJobs variable (so there's no infinite loop there) The loop inside the worker function will eventually stop because the close command for jobs is in a different goroutine, meaning that the worker loop doesn't prevent the close from happening. Edit: The easiest way to think about this is to think of it like this. In the first example the goroutine worked its way through the code, and started the loop that went forever waiting for someone to tell it to stop looping. The command to stop was the thing that it was supposed to do after the loop finished, so it could never get there. Now, the second example, the worker goroutine was sent off to do some work by the main/boss goroutine, and it went into a loop that will stop when the channel closes, it can never close the channel, and there is no other way for the loop to end. However the main goroutine, the one that sent the worker off, it has one loop to execute, that is limited by the numJobs variable, and then it closes the jobs channel, telling the worker goroutine that the loop it is in can finish. More on reddit.com
🌐 r/golang
9
3
August 31, 2023
nice trick: iterate ranges with no memory overhead using []struct{}
221K subscribers in the golang community. Ask questions and post articles about the Go programming language and related tools… More on reddit.com
🌐 r/golang
31
26
June 1, 2014
🌐
Go
go.dev › tour › flowcontrol › 1
For is Go's "while"
Go has only one looping construct, the for loop.
🌐
YourBasic
yourbasic.org › golang › for-loop
5 basic for loop patterns · YourBasic Go
If you skip the init and post statements, you get a while loop. n := 1 for n < 5 { n *= 2 } fmt.Println(n) // 8 (1*2*2*2)
🌐
freeCodeCamp
freecodecamp.org › news › iteration-in-golang
Iteration in Golang – How to Loop Through Data Structures in Go
September 26, 2022 - In programming, iteration (commonly known as looping) is a process where a step is repeated n number of times until a specific condition is met. Just like every other programming language, Golang has a way of iterating through different data ...
🌐
Ardan Labs
ardanlabs.com › blog › 2024 › 03 › for-loops-and-more-in-go.html
For Loops and More in Go
March 12, 2024 - Listing 13 shows a benchmark. On line 24, the code loops b.N times using the new syntax instead of the old for i := 0; i < b.N; i++.
🌐
Google Groups
groups.google.com › g › golang-nuts › c › G7Cm6wRrVkA
Repeat n times when iteration number not needed
I don't make any reference to the ... of the loop, but since the for clauses have to test it against the limit and increment it, I can't use _. So instead, I just used _i, as a signal that the variable's value was unused. Does that seem reasonable, or would it be better Go to just leave it as bog-standard i and not worry about signalling the don't-care condition? -- You received this message because you are subscribed to the Google Groups "golang-nuts" ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-construct-for-loops-in-go
How To Construct For Loops in Go | DigitalOcean
September 13, 2019 - The loop ran 5 times. Initially, it set i to 0, and then checked to see if i was less than 5. Since the value of i was less than 5, the loop executed and the action of fmt.Println(i) was executed. After the loop finished, the post statement of i++ was called, and the value of i was incremented by 1. Note: Keep in mind that in programming we tend to begin at index 0, so that is why although 5 numbers are printed out, they range from 0-4.
Find elsewhere
Top answer
1 of 1
11

To repeat something in Go templates, you may use the {{range}} action. But the {{range}} action expects something it can iterate over, e.g. a slice, array or map.

Passing a zero-value slice

So you have to feed that. But an empty slice which requires no memory is sufficient, e.g. make([]struct{}, n).

The template code:

const templ = `<ul>
{{range $idx, $e := .}}
    <li><a href="/?page={{$idx}}">{{$idx}}</a></li>
{{end}}
</ul>`

Testing it:

tmpl := template.Must(template.New("").Parse(templ))
n := 5
if err := tmpl.Execute(os.Stdout, make([]struct{}, n)); err != nil {
    panic(err)
}

Output (try it on the Go Playground):

<ul>

    <li><a href="/?page=0">0</a></li>

    <li><a href="/?page=1">1</a></li>

    <li><a href="/?page=2">2</a></li>

    <li><a href="/?page=3">3</a></li>

    <li><a href="/?page=4">4</a></li>

</ul>

Using a filled slice

As we can see, indices start from 0. If this is an issue, you may opt to not use the index, but fill the passed slice explicitly with the elements you want. Then the template will look like this:

const templ = `<ul>
{{range .}}
    <li><a href="/?page={{.}}">{{.}}</a></li>
{{end}}
</ul>`

And an example test code that feeds only the odd numbers starting with 2 could look like this:

tmpl := template.Must(template.New("").Parse(templ))
n := 5
values := make([]int, n)
for i := range values {
    values[i] = (i + 1) * 2
}
if err := tmpl.Execute(os.Stdout, values); err != nil {
    panic(err)
}

Output this time (try it on the Go Playground):

<ul>

    <li><a href="/?page=2">2</a></li>

    <li><a href="/?page=4">4</a></li>

    <li><a href="/?page=6">6</a></li>

    <li><a href="/?page=8">8</a></li>

    <li><a href="/?page=10">10</a></li>

</ul>

Using a zero-valued slice and custom function

If you don't want to bother filling the slice and you only need increasing numbers starting from 1, another option would be to register a function that receives a number, adds 1 to it and returns the result. So you may continue to use the indices of a zero-valued slice, and you can call the custom function to obtain a number equal to index+1:

func main() {
    tmpl := template.Must(template.New("").Funcs(template.FuncMap{
        "Add": func(i int) int { return i + 1 },
    }).Parse(templ))
    n := 5
    if err := tmpl.Execute(os.Stdout, make([]struct{}, n)); err != nil {
        panic(err)
    }
}

const templ = `<ul>
{{range $idx, $e := .}}{{$idx := (Add $idx)}}
    <li><a href="/?page={{$idx}}">{{$idx}}</a></li>
{{end}}
</ul>`

Output this time (try it on the Go Playground):

<ul>

    <li><a href="/?page=1">1</a></li>

    <li><a href="/?page=2">2</a></li>

    <li><a href="/?page=3">3</a></li>

    <li><a href="/?page=4">4</a></li>

    <li><a href="/?page=5">5</a></li>

</ul>
🌐
Reddit
reddit.com › r/golang › iterating over an integer?
r/golang on Reddit: iterating over an integer?
December 27, 2023 -

so there's an upcoming feature where you can do for x := range n where n is an integer value. is that an attempt at avoiding a range syntax like Swift, Rust, and others have (m..n or m..=n or [m..n] or m...n) while at the same time having some thing that may in some sense resemble it? what are the possible uses of this construct? what is the rationale behind adding this to the language?

EDIT: what I find weird is that int is a scalar type in Golang, as I understand it, so how can you iterate over it. I mean semantically you cannot. but this is just simple syntactic sugar. I now get that this is a shorthand for one particular and popular case of C-derived for loop scheme where you routinely type out for i := 0; i < n; i++. so you can now just say for i := range n instead. no biggie. it's a very small thing to me.

if this saves someone a search, cool.

🌐
Medium
medium.com › @bramahendramahendra1 › loops-in-golang-the-for-loop-9ab6fbc8c6dc
Loops in Golang: The For Loop. Iteration is an integral part of… | by Brama Mahendra | Medium
September 10, 2023 - Instead, you can use the for loop to achieve the same effect by omitting the initialization and post statements. ... This behaves exactly like the previous loop, printing numbers from 0 to 4.
🌐
GeeksforGeeks
geeksforgeeks.org › loops-in-go-language
Loops in Go Language - GeeksforGeeks
Golang uses control statements ... a single loop that is for-loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times....
Published   November 19, 2019
🌐
Programiz
programiz.com › golang › for-loop
Go for Loop (With Examples)
If we want to print a statement ... we use for loops to clean and simplify complex programs. In Golang, we use the for loop to repeat a block of code until the specified condition is met....
🌐
Dot Net Perls
dotnetperls.com › for-go
Go - for Loop Examples - Dot Net Perls
Suppose we want to repeat a loop once for each element in a slice, but the loop does not use the slice. We can omit all the variables in a for-range loop. Here We repeat a loop 3 times, based on the number of cats in the cats slice.
🌐
Kelche
kelche.co › blog › go › golang-for-loop
Golang for loop (A Complete Guide) - Kelche
January 15, 2023 - Let’s take a look at an example of a for loop in Go. ... In the above example, the init statement is i := 0. The condition is i < 5. The post statement is i++. The code block is fmt.Println(i). The code block is executed 5 times because the condition is true for 5 iterations.
🌐
nixCraft
cyberciti.biz › nixcraft › howto › go programming language › go language for loop examples
Go Language for Loop Examples - nixCraft
April 23, 2014 - Welcome 1 times Welcome 2 times Welcome 3 times Welcome 4 times Welcome 5 times · Here is another example to print sum of all digits using a for loop: // sum.go : golang for loop demo code package main import "fmt" func main() { sum := 0 for i := 1; i<=20; i++ { sum += i } fmt.Printf("Sum = %d\n",sum) }
🌐
TutorialsPoint
tutorialspoint.com › go › go_for_loop.htm
Go - for Loop
A for loop is a repetition control structure. It allows you to write a loop that needs to execute a specific number of times. The syntax of for loop in Go programming language is − The flow of control (working flow) in a for loop is a follows − If
🌐
CodeSignal
codesignal.com › learn › courses › iterations-and-loops-in-go › lessons › mastering-loops-in-go-exploring-for-and-range
Mastering Loops in Go: Exploring `for` and `range`
You take one, count it, and continue the process until all stickers are counted. This is exactly how the basic for loop works in Go! ... After each iteration, post is executed, which changes the state in some way. Now, let's illustrate this with a code snippet that prints numbers 1 through 5:
🌐
TutorialsTeacher
tutorialsteacher.com › go › for-loops
For Loops in Go
In Go, the for loop is used to execute a block of code a specific number of times until a specified condition is met. The for loop is the only loop available in Go lang (no while loops).
🌐
Boot.dev
blog.boot.dev › golang › golang-for-loop
For Loops in Go | Boot.dev
October 12, 2022 - For loops are a programmer’s best friend! They allow us execute blocks of code repeatedly and iterate over collections of items. In Go, there are several different ways to write one. // prints numbers 0 -> 99 for i := 0; i < 100; i++ { fmt.Println(i) }