rust-by-practice/en/src/basic-types/functions.md

1.7 KiB

Functions

  1. 🌟🌟🌟

fn main() {
    // don't modify the following two lines!
    let (x, y) = (1, 2);
    let s = sum(x, y);

    assert_eq!(s, 3);

    println!("Success!")
}

fn sum(x, y: i32) {
    x + y;
}
  1. 🌟
fn main() {
   print();
}

// replace i32 with another type
fn print() -> i32 {
   println!("Success!")
}
  1. 🌟🌟🌟
// solve it in two ways
// DON'T let `println!` works
fn main() {
    never_return();

    println!("Failed!")
}

fn never_return() -> ! {
    // implement this function, don't modify the fn signatures
    
}

Diverging functions

Diverging functions never return to the caller, so they may be used in places where a value of any type is expected.

  1. 🌟🌟

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() -> ! {
    
}
  1. 🌟🌟

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!");
}

You can find the solutions here(under the solutions path), but only use it when you need it