Rust for Beginner
This is just a post for the study of rust on Intro part.
Chap 1
Useful Tools
rustfmtto format the code in particular style.printlnandprintln!are different in rust, the previous one is a function the later one is a macrocargobuild system and package manager.cargo newbackbone of the programcargo buildcompile and buildcargo runbuild and run the codecargo checkcheck compile only, much faster than cargo build, cargo check will speed up the process- Further Studies For interests in cargo book.
TOML: Tom’s Obvious Minimal Languages formatChap 2
let mut guess = String::new();let: create the variable , variables are immutable by defaultlet mut: variable is mutable.&mut guess: assign the value into the guess.- This represent the static type.
cargo update- update a crate to get a new version.
use std::iostandard input output formatuse rand::Rngrandom1..=100Inclusive range for the random
- The error handling, guessing and more are quite interesting.
- Also some error check and handling for the input.
Chap 3
let mutdoes not work with the mutation of the variable type, only valuelet mut spaces = " "; spaces = spaces.len(); // this will give the errorlet guess: u32 = "42".parse().expect("Not a number!");Data type declaration must specify its type au32here.
| int | unsigned int | float (IEEE 754) | | —- | ———— | —————- | | i8 | u8 | f32 | | i16 | u16 | f64 | | i32 | u32 | | | i64 | u64 | | | i128 | u128 | |
- Tuple: type is a general way of grouping together a number of values with a variety of types.
let tup: (i32, f64, u8) = (500, 6.4, 1); - Array:
let a = [1,2,3,4,5]
The function runs:
fn main() {
another_function(5);
}
fn another_function(x: i32) {
println!("The value of x is: {x}");
}
fn main() {
let x = plus_one(5); // could this input variable?
println!("The value of x is: {x}");
}
fn plus_one(x: i32) -> i32 {
x + 1
}
- Control Flow: in case of loop and if, the control flow is a bit more complicated than the
C++we usually use a lot.
// The if statement to judge the number
fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
// A nested for loop example
fn main() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up; // break the outer loop
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}"); //
}
// The result from a loop
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}"); // will give 20
}