Rust - Básico - 05 - Estructuras

Estructuras

Comprensión

  • Sintaxis básica
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

let user1 = User {
    email: String::from("someone@example.com"),
    username: String::from("someusername123"),
    active: true,
    sign_in_count: 1,
};

let mut user1 = User {
    email: String::from("someone@example.com"),
    username: String::from("someusername123"),
    active: true,
    sign_in_count: 1,
};
user1.email = String::from("anotheremail@example.com");

fn build_user(email: String, username: String) -> User {
    User { email, username, active: true, sign_in_count: 1 }
}

let user2 = User {
    email: String::from("another@example.com"),
    ..user1
}

La actualización de estructura mueve user1.username a user2.username; si asignamos otro username al crear user2, user1 no se mueve.

  • Métodos Las funciones dentro de impl son métodos o funciones asociadas. Un método puede llamarse igual que un campo y puede haber varios bloques impl.
#[derive(Debug)]
struct Rectangle { width: u32, height: u32 }

impl Rectangle {
    fn area(&self) -> u32 { self.width * self.height }
    fn width(&self) -> bool { self.width > 0 }
    fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size } }
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

Fuente

https://doc.rust-lang.org/book/ch05-00-structs.html La sintaxis de actualización .. permite crear una instancia usando la mayoría de los valores de otra. Se comporta como una asignación porque mueve los datos: si username es un String, user1 deja de ser válido después de crear user2. Los campos que implementan Copy, como active y sign_in_count, sí permanecen disponibles.