lunes, 3 de julio de 2023

Métodos en Rust


Los métodos son funciones asociadas a un tipo. El argumento self de un método es una instancia del tipo al que está asociado:

struct Rectangle {

    width: u32,

    height: u32,

}


impl Rectangle {

    fn area(&self) -> u32 {

        self.width * self.height

    }


    fn inc_width(&mut self, delta: u32) {

        self.width += delta;

    }

}


fn main() {

    let mut rect = Rectangle { width: 10, height: 5 };

    println!("old area: {}", rect.area());

    rect.inc_width(5);

    println!("new area: {}", rect.area());

}

$ cargo run

   Compiling hello_cargo v0.1.0

   Finished dev [unoptimized + debuginfo] target(s) in 0.28s

     Running `target/debug/hello_cargo`

old area: 50

new area: 75


Podemos definir un constructor : 


struct Rectangle {

    width: u32,

    height: u32,

}


impl Rectangle {


    fn new(width: u32, height: u32) -> Rectangle {

        Rectangle { width, height }

    }


    fn area(&self) -> u32 {

        self.width * self.height

    }


    fn inc_width(&mut self, delta: u32) {

        self.width += delta;

    }

}


fn main() {

    let mut rect = Rectangle::new(10, 5);

    println!("old area: {}", rect.area());

    rect.inc_width(5);

    println!("new area: {}", rect.area());

}



No hay comentarios.:

Publicar un comentario