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. }
  6. impl Person {
  7. fn new(name: String, age: u8) -> Person {
  8. Person { name, age }
  9. }
  10. }
  11. fn main() {
  12. let peter = Person::new(String::from("Peter"), 27);
  13. println!("{peter:?}");
  14. }

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 } } }