Vectores
Arrays redimensionables
Vectores es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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);
}Preguntas frecuentes
¿La lección «Vectores» es gratis?
Sí — el texto completo de «Vectores» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 4 lecciones en total.
¿Qué aprenderé en «Vectores»?
Arrays redimensionables Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Learn Rust Coding?
No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «Vectores»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?
Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.