Un programa RUST de ejemplo

Copper Contributor

Primeros Pasos con Rust

 

Hola programadores Rust,

 

¿Qué cambios necesita este programa en Rust para ejecutarse exitosamente?

 

 

struct Person {
  name: String,
  age: u8,
  genre: char,
}

fn main() {
  // Vector of family members
  let family: Vec<Person> = Vec::new();

  family.push(Person {
    name: "Frank".to_string(),
    age: 23,
    genre: 'M',
  });

  family.push(Person {
    name: "Carol".to_string(),
    age: 25,
    genre: 'F',
  });

  family.push(Person {
    name: "Edwin".to_string(),
    age: 34,
    genre: 'M',
  });

  // Show current info
  println!("-".repeat(50));
  for individual in family {
    println!("{:?}", individual);
  }

  // Add family lastname
  for member in family {
    member.name = member.name + "Thompson";
  }

  // Increase age by 2
  for adult in family {
    adult.age += 2;
  }

  // Show updated info
  println!("-".repeat(50));
  for individual in family {
    match individual {
      'M' => {
        println!("{} is a man {} years old", individual.name, individual.age);
      }
      'F' => {
        println!(
          "{} is a woman {} years old",
          individual.name, individual.age
        );
      }
    }
  }
}

 

 

#rustlang #programming

 

2 Replies

@edandresvan buenas ! 

 

Debajo puedes ver el codigo completo y funcionando. Y un par de detalles sobre los cambios.

En 1er lugar, modifiqué el codigo que escribe lineas en el output por

println!("{}", "-".repeat(50));

En el Struct agregue un atributo para que se pueda mostrar en las sentencias con println!(), e implementé una función Clone() para que se pueda iterar en modo mutable.

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
    genre: char,
}

// implement Clone for Person struct
impl Clone for Person {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            age: self.age,
            genre: self.genre,
        }
    }
}

Y cambié la forma en la que iteras por los elementos del for each. Lo puedes ver todo en el código completo.

 

#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
    genre: char,
}

// implement Clone for Person struct
impl Clone for Person {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            age: self.age,
            genre: self.genre,
        }
    }
}

fn main() {
    // Vector of family members
    let mut family: Vec<Person> = Vec::new();
    family.push(Person {
        name: "Alice".to_string(),
        age: 20,
        genre: 'F',
    });

    family.push(Person {
        name: "Carol".to_string(),
        age: 25,
        genre: 'F',
    });

    family.push(Person {
        name: "Edwin".to_string(),
        age: 34,
        genre: 'M',
    });

    // Show current info
    println!("{}", "-".repeat(50));
    println!("Show current information");
    println!("{}", "-".repeat(50));
    for individual in &family {
        println!("{:#?}", individual);
    }
    println!("{}", "-".repeat(50));

    // Iterate through Family and add a family lastname to the field name
    for individual in &mut family {
        individual.name = format!("{} {}", individual.name, "Thompson");
    }

    println!("{}", "-".repeat(50));
    println!("Show new information after adding the last name");
    println!("{}", "-".repeat(50));
    for individual in &family {
        println!("{:#?}", individual);
    }
    println!("{}", "-".repeat(50));

    // rest of the code goes here ...
}

 Queda completar los últimos pasos. Si tienes problemas o dudas con esos, me avisas ! 

Un saludo !

@elbruno 

 

Hola profe Bruno, gracias por tu respuesta. Estuve probando y ya pude ejecutar el programa con las correcciones. 

 

Adicionalmente, quería compartir lo que encontré mientras probaba el código:

1. Se puede cambiar el nombre de la mascota de estas dos formas:

 

 

member.name = format!("{} {}", member.name, "Thompson");

member.name.push_str(" Thompson");

 

 

2. Para mostrar una mascota usando la característica de Debug, se puede usar esta sintaxis:

 

 

println!("{:?}", individual);

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

 

 

Programa Rust corregido:

 

 

#[derive(Debug)]
struct Person {
  name: String,
  age: u8,
  genre: char,
}

fn main() {
  // Vector of family members
  let mut family: Vec<Person> = Vec::new();

  family.push(Person {
    name: "Frank".to_string(),
    age: 23,
    genre: 'M',
  });

  family.push(Person {
    name: "Carol".to_string(),
    age: 25,
    genre: 'F',
  });

  family.push(Person {
    name: "Edwin".to_string(),
    age: 34,
    genre: 'M',
  });

  // Show current info
  println!("{}", "-".repeat(50));
  for individual in &family {
    println!("{individual:?}");
  }

  // Add family lastname
  for member in &mut family {
    member.name.push_str(" Thompson");
    //member.name = format!("{} {}", member.name, "Thompson");
  }

  // Increase age by 2
  for adult in &mut family {
    adult.age += 2;
  }

  // Show updated info
  println!("{}", "-".repeat(50));
  for individual in family {
    match individual.genre {
      'M' => {
        println!("{} is a man {} years old", individual.name, individual.age);
      }
      'F' => {
        println!(
          "{} is a woman {} years old",
          individual.name, individual.age
        );
      }
      _ => {
        println!("{} is {} years old", individual.name, individual.age);
      }
    }
  }
}