Field Shorthand Syntax
If you already have variables with the right names, then you can create the struct using a shorthand:
1. #[derive(Debug)]
2. struct Person {
3. name: String,
4. age: u8,
5. }
7. impl Person {
8. fn new(name: String, age: u8) -> Person {
9. Person { name, age }
10. }
11. }
13. fn main() {
14. let peter = Person::new(String::from("Peter"), 27);
15. println!("{peter:?}");
16. }
The new function could be written using Self as a type, as it is interchangeable with the struct type name
impl Person { fn new(name: String, age: u8) -> Self { Self { name, age } } }
