Please make this code work
struct Person {
name: String,
age: u32,
hobby: String,
}
impl Person {
fn new(name: &str, age: u32, hobby: &str) -> Self {
Self {
name: name.to_string(),
age,
hobby: hobby.to_string(),
}
}
}
fn main() {
let people = [
Person::new("John", 26, "Music"),
Person::new("Kyle", 22, "Coding"),
Person::new("Tommy", 17, "-"),
];
for (person, i) in people {
println!("index: {}, name: {}, age: {}, hobby: {}", i, person.name, person.age, person.hobby);
//println!("name: {}, age: {}, hobby: {}", person.name, person.age, person.hobby);
};
}
Here's a version on the playground.
struct Person {
name: String,
age: u32,
hobby: String,
}
impl Person {
fn new(name: &str, age: u32, hobby: &str) -> Self {
Self {
name: name.to_string(),
age,
hobby: hobby.to_string(),
}
}
}
fn main() {
let people = [
Person::new("John", 26, "Music"),
Person::new("Kyle", 22, "Coding"),
Person::new("Tommy", 17, "-"),
];
for (index, person) in people.iter().enumerate() {
let Person { name, age, hobby } = person;
println!("index: {index}, name: {name}, age: {age}, hobby: {hobby}");
}
}
1 Like
alice
3
Note that this line:
let Person { name, age, hobby } = person;
is short-hand for this:
let name = &person.name;
let age = &person.age;
let hobby = &person.hobby;
1 Like
system
Closed
4
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.