Rust exercises

Variables

Problem 1

fn main() {
    x = 5;
    println!("x has the value {}", x);
}

Solution 1

fn main() {
    let x = 5;
    println!("x has the value {}", x);
}
x has the value 5

Problem 2

fn main() {
    let x;
    if x == 10 {
        println!("Ten!");
    } else {
        println!("Not ten!");
    }
}

Solution 2

fn main() {
    let x = 10;
    if x == 10 {
        println!("Ten!");
    } else {
        println!("Not ten!");
    }
}
Ten!

Problem 3

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

Solution 3

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

Problem 4

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

Solution 4

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

Problem 5

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

Solution 5

fn main() {
    let mut number = "T-H-R-E-E".len();
    println!("Spell a Number : {}", number);
    number = 3;
    println!("Number plus two is : {}", number + 2);
}
Spell a Number : 9
Number plus two is : 5

Problem 6

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

Solution 6

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