lunes, 14 de agosto de 2023

Constructor en Rust

 


Si ya tiene variables con los nombres correctos, puede crear la estructura usando una abreviatura:

#[derive(Debug)]

struct Person {

    name: String,

    age: u8,

}


impl Person {

    fn new(name: String, age: u8) -> Person {

        Person { name, age }

    }

}


fn main() {

    let peter = Person::new(String::from("Peter"), 27);

    println!("{peter:?}");

}


Podría escribirse usando Self como tipo, ya que es intercambiable con el nombre del tipo de estructura

#[derive(Debug)]

struct Person {

    name: String,

    age: u8,

}

impl Person {

    fn new(name: String, age: u8) -> Self {

        Self { name, age }

    }

}

Podemos tambien definir los campos por defecto: 


#[derive(Debug)]

struct Person {

    name: String,

    age: u8,

}

impl Default for Person {

    fn default() -> Person {

        Person {

            name: "Bot".to_string(),

            age: 0,

        }

    }

}

fn create_default() {

    let tmp = Person {

        ..Person::default()

    };

    let tmp = Person {

        name: "Sam".to_string(),

        ..Person::default()

    };

}


  • Los métodos se definen en el bloque impl.


No hay comentarios.:

Publicar un comentario