Initial commit
This commit is contained in:
6
solutions/01_variables/variables1.rs
Normal file
6
solutions/01_variables/variables1.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
fn main() {
|
||||
// Declaring variables requires the `let` keyword.
|
||||
let x = 5;
|
||||
|
||||
println!("x has the value {x}");
|
||||
}
|
||||
16
solutions/01_variables/variables2.rs
Normal file
16
solutions/01_variables/variables2.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
fn main() {
|
||||
// The easiest way to fix the compiler error is to initialize the
|
||||
// variable `x`. By setting its value to an integer, Rust infers its type
|
||||
// as `i32` which is the default type for integers.
|
||||
let x = 42;
|
||||
|
||||
// But we can enforce a type different from the default `i32` by adding
|
||||
// a type annotation:
|
||||
// let x: u8 = 42;
|
||||
|
||||
if x == 10 {
|
||||
println!("x is ten!");
|
||||
} else {
|
||||
println!("x is not ten!");
|
||||
}
|
||||
}
|
||||
15
solutions/01_variables/variables3.rs
Normal file
15
solutions/01_variables/variables3.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
#![allow(clippy::needless_late_init)]
|
||||
|
||||
fn main() {
|
||||
// Reading uninitialized variables isn't allowed in Rust!
|
||||
// Therefore, we need to assign a value first.
|
||||
let x: i32 = 42;
|
||||
|
||||
println!("Number {x}");
|
||||
|
||||
// It is possible to declare a variable and initialize it later.
|
||||
// But it can't be used before initialization.
|
||||
let y: i32;
|
||||
y = 42;
|
||||
println!("Number {y}");
|
||||
}
|
||||
9
solutions/01_variables/variables4.rs
Normal file
9
solutions/01_variables/variables4.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
fn main() {
|
||||
// In Rust, variables are immutable by default.
|
||||
// Adding the `mut` keyword after `let` makes the declared variable mutable.
|
||||
let mut x = 3;
|
||||
println!("Number {x}");
|
||||
|
||||
x = 5;
|
||||
println!("Number {x}");
|
||||
}
|
||||
9
solutions/01_variables/variables5.rs
Normal file
9
solutions/01_variables/variables5.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
fn main() {
|
||||
let number = "T-H-R-E-E";
|
||||
println!("Spell a number: {}", number);
|
||||
|
||||
// Using variable shadowing
|
||||
// https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing
|
||||
let number = 3;
|
||||
println!("Number plus two is: {}", number + 2);
|
||||
}
|
||||
6
solutions/01_variables/variables6.rs
Normal file
6
solutions/01_variables/variables6.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
// The type of constants must always be annotated.
|
||||
const NUMBER: u64 = 3;
|
||||
|
||||
fn main() {
|
||||
println!("Number: {NUMBER}");
|
||||
}
|
||||
Reference in New Issue
Block a user