Esimerkkiratkaisut

01-variables

fn main() {
    let mut x = 3;
    println!("Number {}", x);
    x = 5; // don't change this line
    println!("Number {}", x);
}

02-variables

fn main() {
    let number = "T-H-R-E-E"; // don't change this line
    println!("Spell a Number : {}", number);
    let number = 3;
    println!("Number plus two is : {}", number + 2);
}

03-variables

fn main() {
    let x: i32 = 5;
    println!("Number {}", x); // Prints: "Number 5"
}

04-variables

const NUMBER: i32 = 3;
fn main() {
    println!("Number {}", NUMBER);
}

05-functions

fn main() {
    call_me(3);
}

fn call_me(num: i32) {
    for i in 0..num {
        println!("Ring! Call number {}", i + 1);
    }
}

06-if

#![allow(unused)]
fn main() {
pub fn bigger(a: i32, b: i32) -> i32 {
    if a > b { a } else { b }
}

// Don't mind this for now
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ten_is_bigger_than_eight() {
        assert_eq!(10, bigger(10, 8));
    }

    #[test]
    fn fortytwo_is_bigger_than_thirtytwo() {
        assert_eq!(42, bigger(32, 42));
    }
}
}

07-if

#![allow(unused)]
fn main() {
// Step 1: Fix the type mismatch and tests `foo_for_fizz` and `default_to_baz`
// Step 2: Get the bar_for_fuzz!

pub fn fizz_if_foo(fizzish: &str) -> &str {
    if fizzish == "fizz" {
        "foo"
    } else if fizzish == "fuzz" {
        "bar"
    } else {
        "baz"
    }
}

// No test changes needed!
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn foo_for_fizz() {
        assert_eq!(fizz_if_foo("fizz"), "foo")
    }

    #[test]
    fn default_to_baz() {
        assert_eq!(fizz_if_foo("literally anything"), "baz")
    }

    #[test]
    fn bar_for_fuzz() {
        assert_eq!(fizz_if_foo("fuzz"), "bar")
    }
}
}

08-ownership

fn main() {
    let vec0 = Vec::new();

    let mut vec1 = fill_vec(vec0);

    println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);

    vec1.push(88);

    println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}

fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
    let mut vec = vec;

    vec.push(22);
    vec.push(44);
    vec.push(66);

    vec
}

09-ownership

// Make me compile only by reordering the lines in `main()`, but without
// adding, changing or removing any of them.

fn main() {
    let mut x = 100;
    x += 1000;
    let y = &x;
    // Note: += is defined by the trait AddAssign:
    // https://doc.rust-lang.org/std/ops/trait.AddAssign.html
    println!("{} == {}", y, x);
}

bonus-ownership

// Make me compile using shadowing: Add a `let` statement.
// No reordering of them lines is necessary.

fn main() {
    let x = 100;
    let y = &x;
    let x = x + 1000;
    println!("1000 + {} == {}", y, x);
}