Functions
- 🌟🌟🌟
2. fn main() {
3. // Don't modify the following two lines!
4. let (x, y) = (1, 2);
5. let s = sum(x, y);
7. assert_eq!(s, 3);
9. println!("Success!");
10. }
12. fn sum(x, y: i32) {
13. x + y;
14. }
- 🌟
1. fn main() {
2. print();
3. }
5. // Replace i32 with another type
6. fn print() -> i32 {
7. println!("Success!");
8. }
- 🌟🌟🌟
1. // Solve it in two ways
2. // DON'T let `println!` work
3. fn main() {
4. never_return();
6. println!("Failed!");
7. }
9. fn never_return() -> ! {
10. // Implement this function, don't modify the fn signatures
12. }
Diverging functions
Diverging functions never return to the caller, so they may be used in places where a value of any type is expected.
- 🌟🌟
2. fn main() {
3. println!("Success!");
4. }
6. fn get_option(tp: u8) -> Option<i32> {
7. match tp {
8. 1 => {
9. // TODO
10. }
11. _ => {
12. // TODO
13. }
14. };
16. // Rather than returning a None, we use a diverging function instead
17. never_return_fn()
18. }
20. // IMPLEMENT this function in THREE ways
21. fn never_return_fn() -> ! {
23. }
- 🌟🌟
2. fn main() {
3. // FILL in the blank
4. let b = __;
6. let _v = match b {
7. true => 1,
8. // Diverging functions can also be used in match expression to replace a value of any value
9. false => {
10. println!("Success!");
11. panic!("we have no value for `false`, but we can panic");
12. }
13. };
15. println!("Exercise Failed if printing out this line!");
16. }
You can find the solutions here(under the solutions path), but only use it when you need it
