Rust:Structs y bloques impl en Rust: métodos y funciones asociadas
Rust•Métodos e impl

Structs y bloques impl en Rust: métodos y funciones asociadas

Aprende la sintaxis de métodos (&self, &mut self) y funciones asociadas como ServerNode::new().

Sintaxis

impl StructName { fn new() -> Self {} fn method(&self) {} }

Parámetros y valores

Componentes clave y valores aceptados para esta estructura:

ParámetroTipoDescripción
&selfReceiverToma prestada la instancia del struct de forma inmutable.
&mut selfReceiverToma prestada la instancia del struct de forma mutable.

Ejemplo de código listo para ejecutar

Ejecutable en Compilra

Ejecuta este ejemplo completo y funcional directamente sin instalar Rust localmente:

struct ServerNode {
    hostname: String,
    port: u16,
    is_active: bool,
}

impl ServerNode {
    // Associated function (constructor)
    fn new(host: &str, port: u16) -> Self {
        ServerNode {
            hostname: String::from(host),
            port,
            is_active: false,
        }
    }

    // Mutable method
    fn start(&mut self) {
        self.is_active = true;
        println!("[NODE] {}:{} is now active.", self.hostname, self.port);
    }

    // Immutable method
    fn status(&self) -> &str {
        if self.is_active { "ONLINE" } else { "OFFLINE" }
    }
}

fn main() {
    let mut node = ServerNode::new("api-primary", 8080);
    println!("Status before: {}", node.status());
    node.start();
    println!("Status after:  {}", node.status());
}
Salida esperada:
Status before: OFFLINE
[NODE] api-primary:8080 is now active.
Status after:  ONLINE

Cómo funciona: paso a paso

  • Líneas 7-15: El constructor ServerNode::new devuelve Self.
  • Líneas 18-21: fn start(&mut self) modifica los campos del struct en su lugar.
  • Líneas 24-26: fn status(&self) toma prestados los campos de forma inmutable.

Conceptos clave

  • Los bloques impl asocian métodos a tipos concretos.
  • Las funciones asociadas sin self se invocan con :: (por ejemplo, Type::new()).
  • Los métodos con &self se invocan con notación de punto (por ejemplo, instance.status()).

Error común: Invocar un método &mut self sobre una variable de struct inmutable

Los métodos con &mut self exigen que la instancia del struct se declare con let mut.

❌ Incorrecto
let node = ServerNode::new(...);
node.start(); // Compile Error: cannot borrow as mutable
✅ Correcto
let mut node = ServerNode::new(...);
node.start();

Tutoriales relacionados de Rust y compilador

Ejecuta y prueba Rust en Compilra

Ejecuta este fragmento de código con entrada estándar pre-suministrada (stdin) en el compilador en la nube de Compilra.

Rust Compilador Online