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
implson métodos o funciones asociadas. Un método puede llamarse igual que un campo y puede haber varios bloquesimpl.
#[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: siusernamees unString,user1deja de ser válido después de crearuser2. Los campos que implementanCopy, comoactiveysign_in_count, sí permanecen disponibles.