AnyCompiler

Structs

Un struct agrupa valores relacionados bajo un tipo con nombre. A diferencia de una tupla, cada campo tiene un nombre, lo que hace que el código que lo crea y lo usa sea autoexplicativo.

struct Person {
    name: String,
    age: u32,
}

fn main() {
    let alice = Person {
        name: String::from("Alice"),
        age: 30,
    };

    println!("{} is {} years old", alice.name, alice.age);
}
Output
Alice is 30 years old

Métodos con impl

Un bloque impl adjunta funciones a un struct. Un método que toma &self toma prestada la instancia sobre la que se llama, leyendo sus campos sin tomar su ownership — rect.area() abajo lee width y height sin consumir rect.

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle { width: 10, height: 5 };
    println!("Area: {}", rect.area());
}
Output
Area: 50

Siguiente: enums y pattern matching — representar un valor que es una de varias variantes distintas, y la garantía de match de que has manejado cada una.

Practice Exercise

Define un struct Book con los campos title: String y price: f64. Añade un método total(&self, quantity: u32) -> f64 que devuelva self.price * quantity as f64. Crea un Book con title "Dune" y price 15.0, luego imprime book.total(3).