General & minimal notes while learning Rust.

Variables

let x = 5; // immutable, can't be changed
let mut y = 10; // can be changed
y = 20;

Shadowing: allows us to reuse the same variable name, often used when converting something from one type to another

let mut guess = String::from("20") // type String
let mut guess: u32 = guess.trim().parse().expect("Not a valid number!");

Strings

It is not possible to change a string literal. It can be passed to a function but the function cannot change the string. It is a fixed string stored in the program’s binary.

let hello = "hello" // a string literal &str, immutable & fixed at compile time

To change a string, we use String. This can be modified by our code.

let mut helloworld = String::new();
helloworld = String::from("Hello");
helloworld.push_str(", world!");
 
// string is now "Hello, world!"

We always need to use references to let multiple areas in our code access one piece of data. References are also immutable by default. If a function should be able to change the variable, we pass a mutable reference.

fn change_string_function(string_to_change: &mut String) {
    string_to_change.push_str(", world!");
}
 
let mut goodbye = String::from("Goodbye");
change_string_function(&mut goodbye) // mutable reference
 
// string is now "Goodbye, world!"

Result type

Result is and enum which can be Ok or Err. If it is Ok it just returns the value that it is holding. If there is an error Rust will not panic automatically, the error is ignored. We need to add .expect() to actually make it panic.

io::stdin().read_line(&mut input).expect("Failed to read the line");

Cargo

When adding dependencies:

[dependencies]
rand = "0.8.5

This basically stands for ^0.8.5 so when building for the first time, it picks the version that is at least 0.8.5 but if there are newer versions that are still below 0.9.0 (which would mean the API could have changed), it will pick those. Then Cargo.lock is written and this kind of update does not happen again unless we explicitly run cargo update. But still, this would not switch to 0.9.0, this would need to be done manually.

Generating docs for the current project + its dependencies:

cargo doc --open