Vec
Vec es el búfer estándar redimensionable asignado al heap:
fn main() { let mut v1 = Vec::new(); v1.push(42); println!("v1: len = {}, capacity = {}", v1.len(), v1.capacity()); let mut v2 = Vec::with_capacity(v1.len() + 1); v2.extend(v1.iter()); v2.push(9999); println!("v2: len = {}, capacity = {}", v2.len(), v2.capacity()); // Canonical macro to initialize a vector with elements. let mut v3 = vec![0, 0, 1, 2, 3, 4]; // Retain only the even elements. v3.retain(|x| x % 2 == 0); println!("{v3:?}"); // Remove consecutive duplicates. v3.dedup(); println!("{v3:?}"); }
Vec implementa Deref<Target = [T]>, lo que significa que puedes llamar a métodos slice en un Vec.
This slide should take about 10 minutes.
Vecis a type of collection, along withStringandHashMap. The data it contains is stored on the heap. This means the amount of data doesn’t need to be known at compile time. It can grow or shrink at runtime.- Ten en cuenta que
Vec<T>también es un tipo genérico, pero no tienes que especificarTde forma explícita. Como siempre sucede con la inferencia de tipos de Rust,Tse estableció durante la primera llamada apush. vec![...]es una macro canónica para usarla en lugar deVec::new()y admite que se añadan elementos iniciales al vector.- Para indexar el vector, se utiliza
[], pero entrará en pánico si se sale de los límites. También se puede usargetpara obtener unaOption. La funciónpopeliminará el último elemento. - Slices are covered on day 3. For now, students only need to know that a value of type
Vecgives access to all of the documented slice methods, too.