You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-06-17 06:37:34 +02:00
Publish Comprehensive Rust 🦀
This commit is contained in:
23
src/structs/field-shorthand.md
Normal file
23
src/structs/field-shorthand.md
Normal file
@ -0,0 +1,23 @@
|
||||
# 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:?}");
|
||||
}
|
||||
```
|
33
src/structs/tuple-structs.md
Normal file
33
src/structs/tuple-structs.md
Normal file
@ -0,0 +1,33 @@
|
||||
# Tuple Structs
|
||||
|
||||
If the field names are unimportant, you can use a tuple struct:
|
||||
|
||||
```rust,editable
|
||||
struct Point(i32, i32);
|
||||
|
||||
fn main() {
|
||||
let p = Point(17, 23);
|
||||
println!("({}, {})", p.0, p.1);
|
||||
}
|
||||
```
|
||||
|
||||
This is often used for single-field wrappers (called newtypes):
|
||||
|
||||
```rust,editable,compile_fail
|
||||
struct PoundOfForce(f64);
|
||||
struct Newtons(f64);
|
||||
|
||||
fn compute_thruster_force() -> PoundOfForce {
|
||||
todo!("Ask a rocket scientist at NASA")
|
||||
}
|
||||
|
||||
fn set_thruster_force(force: Newtons) {
|
||||
// ...
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let force = compute_thruster_force();
|
||||
set_thruster_force(force);
|
||||
}
|
||||
|
||||
```
|
Reference in New Issue
Block a user