# Rust exercises

## Variables

### Problem 1

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

    x = 5;

^ not found in this scope

cannot find value x in this scope

println!("x has the value {}", x);

^ not found in this scope

cannot find value x in this scope


### Solution 1

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

x has the value 5

()


### Problem 2

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

    let x;

^ consider giving x a type

type annotations needed


### Solution 2

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

Ten!

()


### Problem 3

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

    let x = 3;

^ first assignment to x

x = 5; // don't change this line

^^^^^ cannot assign twice to immutable variable

cannot assign twice to immutable variable x

help: make this binding mutable

mut x


### Solution 3

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

Number 3
Number 5

()


### Problem 4

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

    println!("Number {}", x);

^ use of possibly-uninitialized x

borrow of possibly-uninitialized variable: x


### Solution 4

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

Number 1

()


### 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);
}

    number = 3;

^ expected &str, found integer

mismatched types

println!("Number plus two is : {}", number + 2);

^^^^^^ &str

println!("Number plus two is : {}", number + 2);

^ {integer}

println!("Number plus two is : {}", number + 2);

^

cannot add {integer} to &str


### 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);
}
main()

Spell a Number : 9
Number plus two is : 5

()


### Problem 6

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

const NUMBER = 3;

^^^^^^

missing type for const item

help: provide a type for the item

NUMBER: <type>


### Solution 6

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

Number 3

()