public/subjects/question_mark/README.md

72 lines
1.4 KiB
Markdown
Raw Permalink Normal View History

2020-12-28 15:55:34 +00:00
## question_mark
### Instructions
2022-05-27 12:27:19 +00:00
Create the following structures. Each has one element:
2020-12-28 15:55:34 +00:00
2022-05-27 12:27:19 +00:00
- `One`: `first_layer` as type `Option<Two>`.
- `Two`: `second_layer` as type `Option<Three>`
- `Three`: `third_layer` as type `Option<Four>`
- `Four`: `fourth_layer` as type `Option<u16>`.
2020-12-28 15:55:34 +00:00
2022-05-27 12:27:19 +00:00
Beside the structures, you must create a **function** named `get_fourth_layer`, and associate it to the `One` structure. This **function** should return the `Option` value in the `Four` structure.
2021-02-14 05:58:52 +00:00
### Expected Function and structures
2020-12-28 15:55:34 +00:00
```rust
pub struct One {
// expected public fields
}
pub struct Two {
// expected public fields
}
pub struct Three {
// expected public fields
}
pub struct Four {
// expected public fields
}
impl One {
pub fn get_fourth_layer(&self) -> Option<u16> {}
}
```
### Usage
2021-02-14 05:58:52 +00:00
Here is a program to test your function:
2020-12-28 15:55:34 +00:00
```rust
2021-02-14 05:58:52 +00:00
use question_mark::*;
2020-12-28 15:55:34 +00:00
fn main() {
let a = One {
first_layer : Some(Two {
second_layer: Some(Three {
third_layer: Some(Four {
fourth_layer: Some(1000)
})
})
})
};
// output: 1000
println!("{:?}", match a.get_fourth_layer() {
Some(e) => e,
None => 0
})
}
```
And its output:
```console
$ cargo run
2020-12-28 15:55:34 +00:00
1000
$
2020-12-28 15:55:34 +00:00
```
2022-05-27 12:27:19 +00:00
### Notions
- [Unpacking options with ?](https://doc.rust-lang.org/stable/rust-by-example/error/option_unwrap/question_mark.html)