Vectores, Strings y HashMaps
## Objetivos de Aprendizaje
- Trabajar con Vec (arreglos dinamicos)
- Dominar la manipulacion de Strings
- Usar HashMap para almacenamiento clave-valor
- Elegir tipos de coleccion apropiados
## Vectores
### Creando Vectores
```rust
fn main() {
let v: Vec = Vec::new();
let v = vec![1, 2, 3]; // Usando macro
let v = vec![0; 5]; // Cinco ceros
}
```
### Agregando Elementos a un Vector
```rust
fn main() {
let mut v = Vec::new();
v.push(1);
v.push(2);
v.push(3);
v.extend([4, 5, 6]); // Agregar multiples
v.push_str("hello"); // Error: tipo diferente
}
```
### Leyendo Elementos
```rust
fn main() {
let v = vec![1, 2, 3, 4, 5];
let third = v[2]; // Panic si esta fuera de limites
let third = v.get(2); // Devuelve Option<&T>
let third = v.get(2).unwrap(); // Devuelve 3
match v.get(10) {
Some(n) => println!("{}", n),
None => println!("Not found"),
}
}
```
### Iterando sobre Vectores
```rust
fn main() {
let v = vec![1, 2, 3];
// Prestamo inmutable
for i in &v {
println!("{}", i);
}
// Prestamo mutable
let mut v = vec![1, 2, 3];
for i in &mut v {
*i *= 2; // Duplicar cada elemento
}
}
```
### Metodos Utiles
```rust
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
v.pop(); // Remover y devolver el ultimo
v.remove(1); // Remover en indice
v.insert(0, 10); // Insertar en indice
v.clear(); // Remover todos
v.len(); // Longitud
v.is_empty(); // Verificar si esta vacio
v.contains(&3); // Verificar si contiene valor
v.iter().position(|&x| x == 3); // Encontrar indice
v.sort(); // Ordenar (requiere PartialOrd)
v.reverse();
}
```
### Usando Enum en Vector
```rust
fn main() {
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12)),
];
}
```
## Strings
### Creando Strings
```rust
fn main() {
let s = String::new(); // String vacio
let s = "initial".to_string(); // Desde literal
let s = String::from("initial"); // Desde literal
let s = String::with_capacity(10); // Pre-alojado
}
```
### Actualizando Strings
```rust
fn main() {
let mut s = String::from("hello");
s.push(' '); // Agregar char
s.push_str("world"); // Agregar slice de string
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // s1 se mueve, s2 es prestado
// println!("{}", s1); // Error: s1 se movio
let s1 = String::from("Hello");
let s2 = String::from("world");
let s3 = format!("{} {}", s1, s2); // macro format
}
```
### Slices de String
```rust
fn main() {
let s = String::from("hello world");
let hello = &s[0..5]; // hello
let world = &s[6..11]; // world
let hello = &s[..5]; // hello
let world = &s[6..]; // world
}
```
### Iterando sobre Strings
```rust
fn main() {
let s = "hello";
for c in s.chars() {
println!("{}", c);
}
for b in s.bytes() {
println!("{}", b);
}
}
```
### Metodos Utiles de String
```rust
fn main() {
let s = " hello world ";
s.trim(); // Recortar espacios
s.to_uppercase(); // MAYUSCULAS
s.to_lowercase(); // minusculas
s.len(); // Longitud en bytes
s.is_empty(); // Verificar si esta vacio
"hello".contains("ell"); // true
"hello".starts_with("he"); // true
"hello".ends_with("lo"); // true
"hello".replace("l", "r"); // herro
let parts: Vec<&str> = "a,b,c".split(',').collect();
}
```
### String desde Entrada de Usuario
```rust
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect("Failed to read line");
let input = input.trim(); // Remover nueva linea
println!("You entered: {}", input);
}
```
## HashMaps
### Creando HashMaps
```rust
use std::collections::HashMap;
fn main() {
let mut map: HashMap = HashMap::new();
let map = HashMap::from([
("a".to_string(), 1),
("b".to_string(), 2),
]);
}
```
### Agregando Elementos a HashMap
```rust
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
// Solo insertar si la clave no existe
scores.entry(String::from("Blue")).or_insert(20);
scores.entry(String::from("Red")).or_insert(30);
}
```
### Accediendo a Valores
```rust
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
let team = String::from("Blue");
let score = scores.get(&team); // Option<&i32>
match scores.get(&team) {
Some(s) => println!("Score: {}", s),
None => println!("Team not found"),
}
}
```
### Iterando sobre HashMap
```rust
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Blue", 10);
scores.insert("Yellow", 50);
// Iterar sobre pares clave-valor
for (key, value) in &scores {
println!("{}: {}", key, value);
}
// Iterar sobre claves
for key in scores.keys() {
println!("{}", key);
}
// Iterar sobre valores
for value in scores.values() {
println!("{}", value);
}
}
```
### Actualizando Valores
```rust
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Blue", 10);
// Sobrescribir
scores.insert("Blue", 25); // Blue: 25
// Solo insertar si la clave no existe
scores.entry("Yellow").or_insert(50); // Yellow: 50
scores.entry("Yellow").or_insert(100); // Yellow: 50 (sin cambios)
// Actualizar basado en valor anterior
let text = "hello world wonderful world";
let mut word_count = HashMap::new();
for word in text.split_whitespace() {
let count = word_count.entry(word).or_insert(0);
*count += 1;
}
}
```
### Removiendo Entradas
```rust
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Blue", 10);
scores.remove("Blue"); // Remover entrada
scores.clear(); // Remover todos
}
```
## Elegir Tipos de Coleccion
### Vec vs Arreglo
- Usa **arreglo** cuando el tamano es fijo en tiempo de compilacion
- Usa **Vec** cuando el tamano puede crecer o decrecer
### String vs &str
- Usa **&str** (slice de string) cuando no necesitas la propiedad
- Usa **String** cuando necesitas la propiedad o construir strings
### HashMap vs Vec
- Usa **HashMap** cuando necesitas busquedas clave-valor
- Usa **Vec** cuando necesitas datos ordenados o indices
### HashSet
```rust
use std::collections::HashSet;
fn main() {
let mut set = HashSet::new();
set.insert(1);
set.insert(2);
set.insert(3);
set.contains(&2); // true
set.remove(&1);
let a = vec![1, 2, 3];
let b = vec![2, 3, 4];
let intersection: Vec<_> = a.iter().filter(|x| b.contains(x)).collect();
let union: Vec<_> = a.iter().chain(b.iter()).collect();
}
```
## Resumen
- Los vectores (`Vec`) son arreglos dinamicos
- Usa `push` para agregar, `pop` para remover del final
- Usa `get` para acceso seguro, `[]` para acceso con panic
- Los strings (`String`) son expandibles, `&str` es una vista
- Usa `format!` para concatenar strings
- `HashMap` almacena pares clave-valor
- Usa `entry().or_insert()` para insertar-si-no-existe
- `HashSet` almacena valores unicos
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →