Laços for sobre intervalos e itens
Percorra sequências e pares de índices.
Laços for sobre intervalos e itens é uma aula grátis de Zig Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Zig Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Zig Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Iterate with for
A for loop walks through the elements of a slice or array, handing you each item in turn. No manual index needed. 🚶
for (names) |name| {
std.debug.print("{s}\n", .{name});
}The Capture in Pipes
The name between pipes is the capture. On each pass it binds to the current element, giving you a clean, readable loop body.
Capturing by Reference
Prefix the capture with * to get a pointer to each element. That lets you modify items in place rather than copying them.
for (scores) |*s| {
s.* += 1;
}Getting the Index
Add a second sequence to pair items with an index. Zig walks both together, giving you the value and its position.
for (items, 0..) |item, i| {
std.debug.print("{}: {}\n", .{ i, item });
}0.. Is an Index Sequence
The 0.. form produces indices that match the length of the items. It is not a separate array, just a counter walked in lockstep.
Looping a Fixed Count
To repeat a set number of times, iterate over a range like 0..count. The capture holds the current number on each pass.
for (0..3) |n| {
std.debug.print("step {}\n", .{n});
}Ranges Are Half-Open
A range like 0..5 includes 0 but stops before 5, giving exactly five values. This half-open style matches slice lengths perfectly.
Iterating Two Slices
Pass several slices to walk them in parallel. Zig requires them to share the same length, then yields one element from each per pass.
for (keys, values) |k, v| {
put(k, v);
}break and continue Apply
Inside a for loop you can use break to exit early and continue to skip to the next item, just like in a while loop.
for as an Expression
A for can yield a value too. break returns a result, while an else clause supplies the value if the loop completes without breaking.
const idx = for (items, 0..) |x, i| {
if (x == target) break i;
} else null;Pick for or while
Reach for for when you have a sequence to walk. Choose while when looping depends on a condition rather than a collection.
Quick Check
You need both each item and its index in one for loop. Which header does that?
Recap
You ran for loops: capturing items, by-reference edits, indices with 0.., counting ranges, parallel slices, and the value-returning form. 🎯
Perguntas Frequentes
A aula “Laços for sobre intervalos e itens” é grátis?
Sim — o texto completo de “Laços for sobre intervalos e itens” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Zig Academy, atualize para CoddyKit PRO. O curso de Zig Academy inclui 4 aulas no total.
O que vou aprender em “Laços for sobre intervalos e itens”?
Percorra sequências e pares de índices. Você pratica Zig Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Zig Academy?
Nenhuma experiência prévia é necessária. Zig Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Laços for sobre intervalos e itens”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Zig Academy?
Sim. Cada aula de Zig Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- if como instrução e expressão
- Laços while e expressões continue
- Laços for sobre intervalos e itens
- break, continue e laços rotulados