2022-12-21 16:36:30 +01:00
|
|
|
# Field Shorthand Syntax
|
|
|
|
|
|
|
|
If you already have variables with the right names, then you can create the
|
|
|
|
struct using a shorthand:
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct Person {
|
|
|
|
name: String,
|
|
|
|
age: u8,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Person {
|
|
|
|
fn new(name: String, age: u8) -> Person {
|
|
|
|
Person { name, age }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let peter = Person::new(String::from("Peter"), 27);
|
|
|
|
println!("{peter:?}");
|
|
|
|
}
|
|
|
|
```
|
2023-01-23 11:32:46 +00:00
|
|
|
|
|
|
|
<details>
|
|
|
|
|
2023-02-22 06:55:29 -08:00
|
|
|
* The `new` function could be written using `Self` as a type, as it is interchangeable with the struct type name
|
2023-01-23 11:32:46 +00:00
|
|
|
|
2023-03-07 08:11:43 -08:00
|
|
|
```rust,editable
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct Person {
|
|
|
|
name: String,
|
|
|
|
age: u8,
|
|
|
|
}
|
|
|
|
impl Person {
|
|
|
|
fn new(name: String, age: u8) -> Self {
|
|
|
|
Self { name, age }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
* Implement the `Default` trait for the struct. Define some fields and use the default values for the other fields.
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct Person {
|
|
|
|
name: String,
|
|
|
|
age: u8,
|
|
|
|
}
|
|
|
|
impl Default for Person {
|
|
|
|
fn default() -> Person {
|
|
|
|
Person {
|
|
|
|
name: "Bot".to_string(),
|
|
|
|
age: 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fn create_default() {
|
|
|
|
let tmp = Person {
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
let tmp = Person {
|
|
|
|
name: "Sam".to_string(),
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
}
|
|
|
|
```
|
2023-02-22 06:55:29 -08:00
|
|
|
|
|
|
|
* Methods are defined in the `impl` block.
|
|
|
|
* Use struct update syntax to define a new structure using `peter`. Note that the variable `peter` will no longer be accessible afterwards.
|
|
|
|
* Use `{:#?}` when printing structs to request the `Debug` representation.
|
|
|
|
|
2023-01-23 11:32:46 +00:00
|
|
|
</details>
|