2022-02-23 00:49:02 -06:00
|
|
|
# Functions
|
2022-03-02 02:27:16 -06:00
|
|
|
1. πππ
|
2022-02-25 01:41:07 -06:00
|
|
|
```rust,editable
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
// don't modify the following two lines!
|
|
|
|
let (x, y) = (1, 2);
|
2022-03-02 02:27:16 -06:00
|
|
|
let s = sum(x, y);
|
2022-02-25 01:41:07 -06:00
|
|
|
|
|
|
|
assert_eq!(s, 3);
|
2022-03-05 00:48:43 -06:00
|
|
|
|
|
|
|
println!("Success!")
|
2022-02-25 01:41:07 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn sum(x, y: i32) {
|
|
|
|
x + y;
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
|
2022-03-02 02:27:16 -06:00
|
|
|
2. π
|
2022-02-25 01:41:07 -06:00
|
|
|
```rust,editable
|
|
|
|
fn main() {
|
|
|
|
print();
|
|
|
|
}
|
|
|
|
|
|
|
|
// replace i32 with another type
|
|
|
|
fn print() -> i32 {
|
2022-03-05 00:48:43 -06:00
|
|
|
println!("Success!")
|
2022-02-25 01:41:07 -06:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
|
2022-03-02 02:27:16 -06:00
|
|
|
3. πππ
|
2022-02-25 01:41:07 -06:00
|
|
|
|
|
|
|
```rust,editable
|
2022-03-02 02:27:16 -06:00
|
|
|
// solve it in two ways
|
2022-03-05 00:48:43 -06:00
|
|
|
// DON'T let `println!` works
|
2022-02-25 01:41:07 -06:00
|
|
|
fn main() {
|
|
|
|
never_return();
|
2022-03-05 00:48:43 -06:00
|
|
|
|
|
|
|
println!("Failed!")
|
2022-02-25 01:41:07 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn never_return() -> ! {
|
2022-03-02 02:27:16 -06:00
|
|
|
// implement this function, don't modify the fn signatures
|
2022-02-25 01:41:07 -06:00
|
|
|
|
|
|
|
}
|
2022-03-01 08:06:38 -06:00
|
|
|
```
|
|
|
|
|
2022-03-10 07:59:45 -06:00
|
|
|
### Diverging functions
|
|
|
|
Diverging functions never return to the caller, so they may be used in places where a value of any type is expected.
|
|
|
|
|
|
|
|
4. ππ
|
|
|
|
```rust,editable
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
println!("Success!");
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_option(tp: u8) -> Option<i32> {
|
|
|
|
match tp {
|
|
|
|
1 => {
|
|
|
|
// TODO
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
// TODO
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// Rather than returning a None, we use a diverging function instead
|
|
|
|
never_return_fn()
|
|
|
|
}
|
|
|
|
|
|
|
|
// IMPLEMENT this function in THREE ways
|
|
|
|
fn never_return_fn() -> ! {
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
5. ππ
|
|
|
|
```rust,editable
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
// FILL in the blank
|
|
|
|
let b = __;
|
|
|
|
|
|
|
|
let v = match b {
|
|
|
|
true => 1,
|
|
|
|
// Diverging functions can also be used in match expression to replace a value of any value
|
|
|
|
false => {
|
|
|
|
println!("Success!");
|
|
|
|
panic!("we have no value for `false`, but we can panic")
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
println!("Excercise Failed if printing out this line!");
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2022-03-01 08:06:38 -06:00
|
|
|
> You can find the solutions [here](https://github.com/sunface/rust-by-practice)(under the solutions path), but only use it when you need it
|