Indexação e iteração
Acesse e percorra os elementos.
Indexação e iteração é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 2 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 Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Reading by Index
Each element in a vector has a position number called an index. Indexes start at 0, so the first element is index 0.
Read an element with square brackets, like v[0] for the first value.
fn main() {
let v = vec![100, 200, 300];
println!("first = {}", v[0]);
println!("third = {}", v[2]);
}Out of Bounds Panics
Indexing past the end of a vector causes a panic and stops the program. For a vector of length 3, the only valid indexes are 0, 1, and 2.
Asking for v[5] here would crash, so always make sure the index is in range.
Safe Access With get
The get method returns an Option instead of panicking. You get Some(value) if the index exists, or None if it is out of range.
This lets you handle a missing element gracefully.
fn main() {
let v = vec![1, 2, 3];
match v.get(5) {
Some(x) => println!("got {}", x),
None => println!("no such index"),
}
}How Many Elements
The len method gives the number of elements. The last valid index is always len - 1.
Knowing the length helps you loop safely or check bounds before indexing.
fn main() {
let v = vec![5, 6, 7, 8];
println!("length = {}", v.len());
println!("last = {}", v[v.len() - 1]);
}Looping Over Values
The cleanest way to visit every element is a for loop over a reference to the vector. Using &v borrows the vector so it stays usable afterward.
Each pass binds n to a reference of one element.
fn main() {
let v = vec![2, 4, 6];
for n in &v {
println!("value: {}", n);
}
}Looping With Index
When you need the position too, call iter().enumerate(). It yields pairs of (index, value) on each step.
This is perfect for numbered output or rules that depend on position.
fn main() {
let v = vec!["a", "b", "c"];
for (i, item) in v.iter().enumerate() {
println!("{}: {}", i, item);
}
}Changing Each Element
To modify values in place, loop over &mut v and the vector must be mut. Each n is a mutable reference, so you dereference it with * to assign.
Here every element is doubled.
fn main() {
let mut v = vec![1, 2, 3];
for n in &mut v {
*n *= 2;
}
println!("{:?}", v);
}Summing a Vector
Iterators make math easy. The iter().sum() method adds all the elements together.
Rust needs to know the result type, so we annotate the total as i32.
fn main() {
let v = vec![10, 20, 30];
let total: i32 = v.iter().sum();
println!("sum = {}", total);
}First and Last
The first() and last() methods return Option references to the ends of the vector. They give None when the vector is empty.
Using them avoids manual index math and out-of-range crashes.
fn main() {
let v = vec![7, 8, 9];
println!("{:?}", v.first());
println!("{:?}", v.last());
}Searching With contains
To check whether a value is present, use contains. It takes a reference to the value and returns a bool.
This scans the vector and is a quick way to test membership.
fn main() {
let v = vec![3, 6, 9];
println!("has 6? {}", v.contains(&6));
println!("has 5? {}", v.contains(&5));
}Slicing a Range
A slice borrows part of a vector using a range, like &v[1..3]. The start is included and the end is excluded.
Slices let you work with a window of elements without copying them.
fn main() {
let v = vec![10, 20, 30, 40];
let middle = &v[1..3];
println!("{:?}", middle);
}Quick Check
Test your understanding of indexing and iterating.
Recap
You read elements by index, accessed them safely with get, and looped with for, enumerate, and &mut.
You also used sum, first, last, contains, and slices. Next you will grow and shrink vectors.
Perguntas Frequentes
A aula “Indexação e iteração” é grátis?
Sim — o texto completo de “Indexação e iteração” é 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 Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 4 aulas no total.
O que vou aprender em “Indexação e iteração”?
Acesse e percorra os elementos. Você pratica Learn Rust Coding 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 Learn Rust Coding?
Nenhuma experiência prévia é necessária. Learn Rust Coding 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 2 de 4.
Quanto tempo leva a aula “Indexação e iteração”?
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 Learn Rust Coding?
Sim. Cada aula de Learn Rust Coding 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
- Criando e preenchendo vetores
- Indexação e iteração
- Aumentando e diminuindo
- Vetores de structs