Tags: rust
Learn Rust on JetBrains Academy
I am using Rust Rover IDE for this course. To open the course
Welcome screen → Learn → Learn Rust.
A simple hello world program.
fn main() {
println!("hello, world");
}
Why does
println!have a!? It's a macro call instead of a fucntion call.
By default, variables are immutable in Rust.
fn main() {
let x = 5;
x = 6; // Compile error
}
Add mut to make a variable mutable.
fn main() {
let mut x = 5;
println!("{x}");
x = 6;
println!("{x}");
}
When to use mutation? If you have a large data structure, mutation will help save memory as it won't be making copies of it. However for smaller data structure, immutablity is prefered as it will make more safe and functional.
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
Redeclare a variable with same name.
fn main() {
let x = "hello";
println!("{x}");
let x = 3;
println!("{x}");
}
How is this different from using mut?
fn main() {
let mut x = "hello";
x = 3; // Compile error
}
let creates a new binding each time, so the new x can have a different type. With mut, I'm assigning a new value to the same x, so the type has to stay the same.
Rust is statically typed. The compiler knows the types at compile time and can often figure them out from the code. Scalar types represent a single value.
In Go, a declared bool gets the zero value false. In Rust, a local variable can be declared before it's initialized, but it needs a value before I can read it.
fn main() {
let is_evening: bool;
}
This compiles with an unused variable warning. What happens if I try to use it?
fn main() {
let is_evening: bool;
if is_evening {
println!("it's evening");
}
}
Compile error. is_evening hasn't been initialized.