Using Structs in Rust
Level: medium (score: 3)
💡 Individual exercises are great, but nothing beats building a real-world app with Rust.
Check out our Rust Intro Cohort Program!
Update the Person
struct to model a person with name
, age
, and email
fields. Implement a method greet
that returns a greeting string using the struct's fields.
Given a Person
instance with the following fields, it should return the following greeting:
let person = Person { name: String::from("John"), age: 30, email: String::from("john@example.com"), }; let greeting = person.greet()
This will print: Hello, my name is John and I am 30 years old. You can contact me at john@example.com
struct Person {
// Define fields for name, age, and email
}
impl Person {
// Implement a method to return a greeting string
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_person_greet() {
let person = Person {
name: String::from("Alice"),
age: 28,
email: String::from("alice@example.com"),
};
// Test the greet method
let greeting = person.greet();
assert_eq!(
greeting,
"Hello, my name is Alice and I am 28 years old. You can contact me at alice@example.com"
);
}
#[test]
fn test_person_greet_different_person() {
let person = Person {
name: String::from("Bob"),
age: 45,
email: String::from("bob@example.com"),
};
// Test the greet method for a different person
let greeting = person.greet();
assert_eq!(
greeting,
"Hello, my name is Bob and I am 45 years old. You can contact me at bob@example.com"
);
}
}