Vetores
Matrizes redimensionáveis
Vetores é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 1 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.
What Is a Vector?
A Vec<T> is a growable array. Unlike a fixed-size array, a vector can grow or shrink at runtime.
All elements must be the same type T.
fn main() {
let v: Vec<i32> = Vec::new();
println!("empty vector with length {}", v.len());
}Creating with vec!
The vec! macro is the easiest way to create a vector with initial values.
fn main() {
let numbers = vec![1, 2, 3, 4];
println!("{:?}", numbers);
}Adding Elements
Use push to append an element to the end. The vector must be mut to change it.
fn main() {
let mut v = Vec::new();
v.push(10);
v.push(20);
v.push(30);
println!("{:?}", v);
}Removing Elements
pop removes and returns the last element wrapped in an Option. It returns None if the vector is empty.
fn main() {
let mut v = vec![1, 2, 3];
let last = v.pop();
println!("removed {:?}, now {:?}", last, v);
}Accessing by Index
Index a vector with square brackets, just like an array. An out-of-range index causes a panic.
fn main() {
let v = vec!["a", "b", "c"];
println!("first {}", v[0]);
println!("third {}", v[2]);
}Safe Access with get
The get method returns an Option instead of panicking, which is safer for unknown indices.
fn main() {
let v = vec![10, 20, 30];
match v.get(5) {
Some(x) => println!("found {}", x),
None => println!("no element there"),
}
}Iterating a Vector
Loop over a vector's elements with a for loop. Use & to borrow each element without taking ownership.
fn main() {
let v = vec![100, 200, 300];
for item in &v {
println!("item {}", item);
}
}Mutating While Iterating
Iterate with &mut to modify each element in place. Dereference with * to change the value.
fn main() {
let mut v = vec![1, 2, 3];
for item in &mut v {
*item *= 10;
}
println!("{:?}", v);
}Vector Length and Emptiness
Use len() for the number of elements and is_empty() to check if there are none.
fn main() {
let v = vec![5, 6];
println!("len {} empty {}", v.len(), v.is_empty());
}Common Vector Methods
Vectors offer many helpers:
contains— check membership.first/last— get ends as Option.sort— order the elements.
fn main() {
let mut v = vec![3, 1, 2];
v.sort();
println!("{:?} contains 2: {}", v, v.contains(&2));
}Summing with Iterators
Combine vectors with iterator methods to compute totals concisely.
fn main() {
let v = vec![10, 20, 30, 40];
let total: i32 = v.iter().sum();
println!("total {}", total);
}Quick Check
Recall the method that grows a vector.
Recap
Vectors in Rust:
Vec<T>is a growable, same-type list.- Create with
Vec::new()orvec![...]. pushadds,popremoves from the end.- Access with
[]or safely withget. - Iterate with
for x in &v.
fn main() {
let mut scores = vec![80, 90];
scores.push(100);
let avg: i32 = scores.iter().sum::<i32>() / scores.len() as i32;
println!("average {}", avg);
}Perguntas Frequentes
A aula “Vetores” é grátis?
Sim — o texto completo de “Vetores” é 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 “Vetores”?
Matrizes redimensionáveis 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 1 de 4.
Quanto tempo leva a aula “Vetores”?
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.