Lesson contents

Go — Post-test loops with for and break

An unconditional for loop with a stop check at the end provides post-test behavior in Go. The first poll happens before readiness is checked.

A simple example

Print first, then test

  1. Start with n starts at 1
  2. Do this Print n, add 1
  3. Result Stop at 4
The first print happens before the stopping test. The loop prints 1, 2 and 3 on separate lines.
main.go
package main

import "fmt"


func main() {
    n := 1
    for {
        fmt.Println(n)
        n++
        if n > 3 {
            break
        }
    }
}
Output
1
2
3
Advertisements

Poll until ready or the attempt limit

Count the first poll for every request, even if it is already ready. Stop after success or after the configured maximum number of attempts. break exits the loop when either success or the limit is reached. Keep the stop check below the work that must happen at least once.

First check: Busy. Second check: Ready. Checks made: 2.
Check a printer until it is ready

A print desk checks the printer once before deciding whether to check again. If the printer answers ready on the second check, the loop stops there. A limit of three checks keeps an offline printer from holding up the desk.

Run the example

Use Go 1.21 or later. Run these commands from the directory containing the example.

go run main.go
main.go
package main

import (
	"fmt"
)

func pollCount(readyOn, limit int) int {
	attempts := 0
	for {
		attempts++
		if attempts >= readyOn || attempts >= limit {
			break
		}
	}
	return attempts
}

func main() {
	fmt.Println(pollCount(5, 1))
	fmt.Println(pollCount(2, 3))
	fmt.Println(pollCount(8, 3))
}
Output
1
2
3

With one permitted attempt, the first case stops at 1. The second becomes ready on attempt 2. The last case never reaches readiness within its three-attempt limit.

Apply the loop to a retry queue

Simulate a job using prerecorded replies. T means a temporary failure, S means success, and X means permanent rejection. Process at most two replies per job. Stop on S or X and report how many replies were consumed.

First reply: Temporary failure. Next reply: Success. Attempts used: 2.
Handle a temporary print failure

A queue can retry a temporary failure once under a two-attempt limit. A temporary failure followed by success finishes the job. A permanent rejection stops the job immediately and leaves the next reply unused.

Run this example

Save this program as main.go and run it separately.

go run main.go
main.go
package main

import "fmt"

func process(responses string, limit int) (string, int) {
	used := 0
	for _, response := range responses {
		if used == limit {
			break
		}
		used++
		switch response {
		case 'S':
			return "sent", used
		case 'X':
			return "rejected", used
		}
	}
	if used == limit {
		return "limit reached", used
	}
	return "no response", used
}

func main() {
	jobs := []struct{ id, responses string }{
		{"A", "TS"}, {"B", "XS"}, {"C", "TTS"}, {"D", ""},
	}
	for _, job := range jobs {
		outcome, attempts := process(job.responses, 2)
		fmt.Printf("%s: %s (%d)\n", job.id, outcome, attempts)
	}
}
Output
A: sent (2)
B: rejected (1)
C: limit reached (2)
D: no response (0)

Job A succeeds on its second reply. B stops at the rejection before its later success. C reaches the attempt limit with a success still unread. D has no recorded reply, so its count stays zero. Try raising the limit to three: only C changes, succeeding on the third reply.

Try it yourself

A request is ready on the first poll and allows three attempts. How many polls run?

Check your answer

Exactly one. The success check happens after the first poll. The example assumes a positive attempt limit.

Go language specification

Related tags

  • Go
  • post-test loops
  • retries
  • termination