In this post, I will share what I have learned about the Rust language. The primary resource for my learning will be the Rust Book.
In the Rust Book-Foreword, the advantages of the Rust language are described as follows:
My personal thoughts on the Rust language:
Now, let’s dive deeper into the Rust language.
let
keyword.mut
keyword when declaring it.// This will cause an error.
let testVar = 5;
testVar = 6;
// This will not cause an error.
let mut testVar = 5;
testVar = 6;
const
keyword.fn main() {
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}
mut
keyword with them.// Using the `mut` keyword with constants will cause an error.
fn main() {
const mut THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
}
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
fn main() {
let testVar = 10;
}
// The type of the variable is inferred automatically.
fn main() {
// This could be of type i8 to i128, or u8 to u128,
// but by default, if the type is not specified, an integer is of type i32.
let x = 2;
// For floating-point numbers, the default type is f32.
let y = 3.0; // f32
}
// This will cause a type error.
fn main() {
let mut testVar = " ";
testVar = 5;
}
// Redeclaring a variable with the same name is not an error (Shadowing).
fn main() {
let testVar = " ";
let testVar = 5;
}
```rust
// To delve deeper, if a shadowed variable occupies heap space...
fn main() {
{
let s = String::from("hello"); // s uses heap memory
let s = 5; // The previous s goes out of scope, and drop is called.
} // The new s goes out of scope here.
}
Scalar Types
Rust has four scalar types: Integer, floating-point number, Boolean, and character. These types are managed on the stack.
Compound Types
Rust supports two compound types: Tuple and Array. The difference is that a Tuple allows each element to have a different data type, while an Array requires all elements to have the same data type.
fn main() {
// Each element can have a different type.
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
fn main() {
// Even without specifying types, type inference will determine each element's type.
let tup = (500, 6.4, 1);
// You can also decompose a Tuple.
let (x, y, z) = tup;
}
fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
let six_point_four = x.1;
let one = x.2;
}
fn main() {
// All elements must have the same type.
let months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
}
fn main() {
// You can explicitly specify the type and length.
let a: [i32; 5] = [1, 2, 3, 4, 5];
}
fn main() {
let a = [1, 2, 3, 4, 5];
let first = a[0];
let second = a[1];
}