.\" Made by website/plain/build.mjs from website/words/for.md; change that file. .TH SG-FOR 7 2026-11-28 "SG" "SG reference" .SH NAME for \- goes over the numbers of a range or the items of a collection, one round for each .SH SYNOPSIS .TP \fBfor i in a..b\fR the numbers from a up to b, without b .TP \fBfor i in (a..b).reversed()\fR the same numbers, the last first .TP \fBfor _ in 0..n\fR n rounds, with no name .TP \fBfor x in read xs\fR each item of xs, lent to look at .TP \fBfor x in ref xs\fR each item of xs, lent to change .TP \fBfor x in xs\fR xs handed over: each item is owned by its round .TP \fBfor e in read map\fR each entry of a HashMap, with e.key and e.value .TP \fBfor c in text.chars()\fR an iterator: the characters, words or lines of a text .TP \fBfor x in channel\fR each item a channel receives, until every sender has ended .TP \fBname: for ...\fR a loop with a name, for break name and continue name .SH DESCRIPTION \fBfor\fR runs its block once for each number of a range or each item of a collection. It goes over a range \fBa..b\fR, a \fBList\fR, an array, a slice, a \fBHashMap\fR, a \fBHashSet\fR, a \fBChannel\fR and the iterators of a text, such as \fBchars()\fR and \fBlines()\fR\&. Between the name and the items stands \fBin\fR\&. There is one name: for the positions too, go over \fB0..xs.length()\fR and read \fBxs[i]\fR\&. .PP A range goes up to its end and leaves the end out; a range whose end is not above its start gives no round. Its ends are found once, before the first round. The name of a range is a copy of the count, made at the start of each round: the body may change it, and that changes only the round it is in. Its type is the type of the ends. .PP The items of a collection are taken as a \fBmatch\fR takes a value. \fBfor x in read xs\fR lends each item to look at, \fBfor x in ref xs\fR lends each item to change, and \fBfor x in xs\fR hands the collection over, so \fBxs\fR is gone after the loop. When \fBxs\fR is already a borrow, the items are lent the same way. While the loop runs, \fBxs\fR cannot be changed or moved. .PP \fBbreak\fR leaves the loop and \fBcontinue\fR goes on with the next round. A loop with a name, \fBouter: for ...\fR, can be left or gone on with from a loop inside it: \fBbreak outer\fR, \fBcontinue outer\fR\&. .SH EXAMPLES .SS "Counting" .RS 4 .nf void main() { long total = 0 for i in 1..5 { total += i * i } print(total) for _ in 0..3 { print("again") } for n in 5..5 { print(n) } } .fi .RE .PP .RS 4 .nf 30 again again again .fi .RE .PP \fB1..5\fR is 1, 2, 3 and 4. \fB_\fR stands for a name the body does not need. \fB5..5\fR has no number in it, so its loop runs no round. .SS "The count is a copy for each round" .RS 4 .nf void main() { for i in 0..4 { i += 1 print(i) } } .fi .RE .PP .RS 4 .nf 1 2 3 4 .fi .RE .PP Adding to \fBi\fR changes only the round it is in; the next round starts from the next number of the range. .SS "The items of a list, lent" .RS 4 .nf void main() { var prices = List { 100, 250, 80 } for price in ref prices { price = price * 2 } for price in read prices { print(price) } print(prices.length()) } .fi .RE .PP .RS 4 .nf 200 500 160 3 .fi .RE .PP \fBref prices\fR lends each item to change, and writing to \fBprice\fR writes into the list. \fBread prices\fR only looks. The list is still there after both loops. .SS "A list handed over" .RS 4 .nf void main() { var names = List { "ada", "grace" } var shouting = List() for name in names { shouting.add(name.toUpper()) } print(shouting) } .fi .RE .PP .RS 4 .nf ["ADA", "GRACE"] .fi .RE .PP Without \fBread\fR or \fBref\fR, the list is handed over to the loop, and each \fBname\fR is owned by its round. \fBnames\fR cannot be used after the loop. .SS "Positions and items" .RS 4 .nf void main() { var names = List { "ada", "grace" } for i in 0..names.length() { names.add($"{names[i]}!".toString()) print($"{i}: {names[i]}") } print(names) } .fi .RE .PP .RS 4 .nf 0: ada 1: grace ["ada", "grace", "ada!", "grace!"] .fi .RE .PP A range over the positions borrows nothing, so the list may change inside the loop. The end, \fBnames.length()\fR, is found once before the first round, so the items added are not gone over. \fBi\fR is a \fBnint\fR, the type of \fBlength()\fR\&. .SS "A map and a set" .RS 4 .nf void main() { var ages = HashMap { {"ada", 36}, {"grace", 85} } for item in ref ages { item.value += 1 } var names = List() int total = 0 for item in read ages { names.add(item.key.clone()) total += item.value } names.sort() print($"{names} {total}") var seen = HashSet { 3, 5, 8 } int sum = 0 for n in read seen { sum += n } print(sum) } .fi .RE .PP .RS 4 .nf ["ada", "grace"] 123 16 .fi .RE .PP Each item of a map has a \fBkey\fR and a \fBvalue\fR; \fBref\fR changes the values, never the keys. A map and a set keep no order, so the names are sorted before they are printed. .SS "Arrays and slices" .RS 4 .nf int total(read int[] items) { int sum = 0 for x in items { sum += x } return sum } void main() { var primes = int[4] { 2, 3, 5, 7 } var xs = List { 10, 20, 30, 40 } for x in xs[1..3] { print(x) } print(total(read primes)) print(total(xs[2..])) print(xs.length()) } .fi .RE .PP .RS 4 .nf 20 30 17 70 4 .fi .RE .PP \fBxs[1..3]\fR is a window onto the items at 1 and 2, lent to the loop. \fBitems\fR is already a borrow, so the loop in \fBtotal\fR lends its items too. .SS "The characters, bytes, words and lines of a text" .RS 4 .nf void main() { for c in "año".chars() { print(c) } for b in "año".asBytes() { print(b) } for word in " to be or\etnot ".splitWhitespace() { print(word) } for line in "one\entwo\en".lines() { print(line) } } .fi .RE .PP .RS 4 .nf a ñ o 97 195 177 111 to be or not one two .fi .RE .PP A \fBstring\fR is not gone over by itself: \fBchars()\fR gives its characters, \fBasBytes()\fR its bytes (\fBñ\fR is two bytes in UTF-8), \fBsplitWhitespace()\fR its words and \fBlines()\fR its lines. .SS "Counting down" .RS 4 .nf void main() { var order = List() for i in (1..6).reversed() { order.add(i) } print(order) var xs = List { "a", "b", "c" } for i in (0..xs.length()).reversed() { print($"{i} {xs[i]}") } } .fi .RE .PP .RS 4 .nf [5, 4, 3, 2, 1] 2 c 1 b 0 a .fi .RE .PP \fB(a..b).reversed()\fR counts from \fBb \- 1\fR down to \fBa\fR\&. It is the safe way down to 0: the count never goes below \fBa\fR, so an unsigned count stops at 0 without wrapping. A range in brackets is written only so, at the head of a \fBfor\fR\&. .SS "break and continue" .RS 4 .nf void main() { for n in 1..20 { if n % 3 == 0 { continue } if n > 7 { break } print(n) } } .fi .RE .PP .RS 4 .nf 1 2 4 5 7 .fi .RE .PP \fBcontinue\fR skips the rest of the round for 3 and 6; \fBbreak\fR leaves the loop at 8. .SS "A loop with a name" .RS 4 .nf void main() { var grid = List> { List { 1, 2, 3 }, List { 4, 5, 6 }, List { 7, 8, 9 } } search: for row in 0..grid.length() { for col in 0..grid[row].length() { if grid[row][col] == 5 { print($"found at {row}, {col}") break search } } } rows: for row in read grid { for value in read row { if value % 2 == 0 { print($"the first even item is {value}") continue rows } } print("no even item") } } .fi .RE .PP .RS 4 .nf found at 1, 1 the first even item is 2 the first even item is 4 the first even item is 8 .fi .RE .PP \fBbreak search\fR leaves both loops at once. \fBcontinue rows\fR goes on with the next row, so \fB"no even item"\fR is printed only for a row where the inner loop ended by itself. .SS "Over what try opens" .RS 4 .nf Result, string> numbers(bool good) { if !good { return Error("no numbers".clone()) } return Ok(List { 1, 2, 3 }) } Result sum(bool good) { int total = 0 for n in try numbers(good) { total += n } return Ok(total) } void main() { print(sum(true) ?? -1) print(sum(false) ?? -1) } .fi .RE .PP .RS 4 .nf 6 -1 .fi .RE .PP The collection is computed once, before the first round. When \fBnumbers\fR gives an error, \fBtry\fR hands it to the caller there, and no round runs. .SS "Over a channel" .RS 4 .nf void greet(Sender out) { _ = out.send("hello".clone()) _ = out.send("world".clone()) } void main() { var words = Channel(4) var task = Task.run(greet, words.sender()) for word in words { print(word) } task.wait() } .fi .RE .PP .RS 4 .nf hello world .fi .RE .PP A \fBfor\fR over a channel receives each item as it comes, and ends when every sender has ended: here, when \fBgreet\fR returns. .SH "WHAT THE COMPILER REFUSES" .SS "A text by itself" .RS 4 .nf void main() { for c in "hello" { print(c) } } .fi .RE .PP .RS 4 .nf error: `for` does not go over a `string` --> example.sg:2:14 2 | for c in "hello" { | ^^^^^^^ hint: the characters: `for c in "hello".chars()`; the bytes: `for b in "hello".asBytes()` .fi .RE .SS "Something that has no items" .RS 4 .nf void main() { int count = 3 for i in count { print(i) } } .fi .RE .PP .RS 4 .nf error: `for` goes over a range `a..b`, a `List`, an array, a slice, a `HashMap`, a `HashSet`, a `Channel` or an iterator such as `text.chars()` or `reader.lines()`, found `int` --> example.sg:3:14 3 | for i in count { | ^^^^^ hint: the numbers from 0 up to it: `for i in 0..count` .fi .RE .PP The rounds of a count are written \fBfor i in 0..count\fR\&. .SS "A range that takes its end" .RS 4 .nf void main() { for i in 1..=3 { print(i) } } .fi .RE .PP .RS 4 .nf error: `..=` is written only in a pattern; a `for` goes up to its end, without it --> example.sg:2:15 2 | for i in 1..=3 { | ^^^ hint: `for i in a..b + 1` .fi .RE .SS "Changing the collection the loop goes over" .RS 4 .nf void main() { var queue = List { 1, 2, 3 } for job in read queue { if job == 2 { queue.add(4) } } } .fi .RE .PP .RS 4 .nf error: `queue` cannot be changed or moved while a `for` goes over `queue` --> example.sg:5:13 5 | queue.add(4) | ^^^^^ the loop is here: --> example.sg:3:16 3 | for job in read queue { | ^^^^^^^^^^ hint: go over the positions instead (`for i in 0..queue.length()`), or keep the changes in another list until the loop ends .fi .RE .PP A list that grew inside the loop could move its items to new memory under the loop's feet. .SS "A list used after the loop took it" .RS 4 .nf void main() { var names = List { "ada", "grace" } for name in names { print(name) } print(names.length()) } .fi .RE .PP .RS 4 .nf error: `names` was moved and can no longer be used --> example.sg:6:11 6 | print(names.length()) | ^^^^^ it was moved here: --> example.sg:3:17 3 | for name in names { | ^^^^^ .fi .RE .PP \fBfor name in read names\fR would only lend the items, and keep the list. .SS "The items of a set, changed" .RS 4 .nf void main() { var seen = HashSet { 1, 2 } for n in ref seen { n += 1 } } .fi .RE .PP .RS 4 .nf error: the items of a `HashSet` cannot be changed in place: the set finds them by their value --> example.sg:3:14 3 | for n in ref seen { | ^^^^^^^^ hint: go over it with `read`, and use `remove` and `add` after the loop .fi .RE .SS "A name nothing reads" .RS 4 .nf void main() { for i in 0..3 { } } .fi .RE .PP .RS 4 .nf error: `i` is never used --> example.sg:2:9 2 | for i in 0..3 { | ^ hint: when the loop needs no name: `for _ in 0..3` .fi .RE .SS "A loop name nothing uses" .RS 4 .nf void main() { outer: for i in 0..3 { for j in 0..3 { if j == 1 { break } print(i + j) } } } .fi .RE .PP .RS 4 .nf error: no `break outer` or `continue outer` uses the name of this loop --> example.sg:2:5 2 | outer: for i in 0..3 { | ^^^^^ hint: a loop needs a name only for a loop inside it to leave it: remove `outer:` .fi .RE .SS "A name that hides another" .RS 4 .nf void main() { var i = 5 for i in 0..3 { print(i) } print(i) } .fi .RE .PP .RS 4 .nf error: `i` is already a local variable of a block around this one, and a new name cannot hide it .fi .RE .SH "SEE ALSO" .BR sg-in (7), .BR sg-while (7), .BR sg-break (7), .BR sg-continue (7), .BR sg-read (7), .BR sg-ref (7) .PP https://sg\-lang.org/reference/for.html