Skip to content
Loops with for
step 1/5

Reading — step 1 of 5

Learn

~2 min readControl Flow

Loops with for

Go has exactly one loop keyword. No while, no do-while, no until — every loop in every Go program ever written is a for. The trick is that for wears four costumes, and choosing the right one is most of loop fluency.

Form 1: the classic three-part

go

i exists only inside the loop. As with if: no parens, braces mandatory.

Form 2: condition only (the while)

go

Drop the init and post, keep the condition — that's while in Go. Same keyword, so nothing new to learn.

Form 3: infinite

go

No condition means loop forever — the idiomatic heart of every server and worker. You leave with break (exit the loop) or return (exit the function). continue skips to the next iteration:

go

Form 4: range (the one you'll use most)

range iterates collections, yielding index and element:

go

The _ (blank identifier) matters because Go's unused-variable rule applies to range variables too — _ is how you say "I know, I don't want it." Over strings, range decodes runes (as you saw in String Basics); over maps (next chapter), it visits keys — in deliberately random order.

One subtlety worth planting early: v is a copy of the element. Mutating v doesn't touch the slice — nums[i] = v * 2 does. When a loop "isn't changing anything," this is almost always why.

Your exercise: sum 1 to N

Read n, add up 1 + 2 + … + n, print the total. The pattern being drilled is the accumulator:

go

Three details graders catch: start total at 0 before the loop (inside means it resets every pass); mind the boundary — i <= n, not i < n, or you're summing to N−1 (the single most common off-by-one in existence); and print only after the loop ends. Yes, Gauss's n*(n+1)/2 computes it without a loop — clever, correct, and not what the next twelve exercises will build on. The accumulator is; make it muscle memory.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…