Welcome back to Rust Programming, Episode 2. After covering memory management and the stack in Episode 1, this lesson introduces variables, constants, tuples, arrays, functions, if/else, loops, collections, hash maps, structs, modules, traits, enums and closures.
Declaring variables
Rust uses let and mut when declaring variables. By default, a variable declared with let is immutable; mut makes it mutable. For example, let x = 5; declares x with the value 5, and the value cannot be changed. With let mut x = 5;, the value can be changed.
let and mut
Use let to declare an immutable variable whose value cannot be changed after it is first assigned. Use mut to declare a mutable variable whose value can change.
Specifying a type
You can specify a variable’s type with a colon followed by the type, as in let x: i32 = 5;. This declares x as a 32-bit integer and assigns it the value 5.
Type inference
Rust can infer a variable’s type from the value assigned to it. For example, in let x = 5;, Rust infers i32 for x because 5 is an integer literal.
Declaring multiple variables
The source shows this as a multiple-variable declaration: let x = 10, y = 20;. In the example, x is 10 and y is 20.
Constants
Rust constants are declared with const. A constant cannot be changed after it is assigned, and its type must always be specified.
Declaring a constant
Use const, followed by the constant’s name, type and value. For example: const PI: f64 = 3.14;
Specifying the type
A constant must always have a type. For example, f64 is a floating-point type.
Tuples
A tuple can store values of different types in one variable.
Declaring a tuple
Use parentheses and separate the values with commas, as in let x = (1, "hello", 3.14);
Accessing tuple values
Tuple indexes start at 0. For x = (1, "hello", 3.14), x.0 is 1, x.1 is "hello" and x.2 is 3.14.
Arrays
An array stores multiple values of the same type.
Declaring an array
Use square brackets and separate values with commas, as in let x = [1, 2, 3, 4, 5];
Specifying an array type
You can specify an array’s type and length. For example, let x: [i32; 5] = [1, 2, 3, 4, 5]; declares an array of five i32 values.
Setting an initial value
The expression let x = [0; 5]; creates an array with five values, each set to 0.
Functions
A function is a block of code that performs a particular task.
Declaring a function
Declare a function with fn, followed by its name, any parameters and their types, and its return type if it has one. For example:
fn get_number() -> i32 {
10
}
Returning a value
You can return a value from a function using return:
fn get_number() -> i32 {
return 10;
}
Using a return expression
A function can also return its final expression without using the return keyword:
fn get_number() -> i32 {
10 // no semicolon needed
}
If/else
Use if/else to control program flow based on a condition.
Writing if/else
In Rust, an if/else condition does not need parentheses, but braces are required:
if x > 5 {
println!("x is greater than 5");
} else {
println!("x is less than or equal to 5");
}
Using an if/else expression
An if/else can also be used as an expression:
let number = if x > 5 { 10 } else { 20 };
Loops
Loops repeat a block of work.
while
A while loop repeats until its condition becomes false:
let mut i = 0;
while i < 5 {
println!("{}", i);
i += 1;
}
loop
A loop repeats until a break statement exits it:
loop {
println!("Hello");
break;
}
for
A for loop iterates over a collection such as an array or range:
for i in 0..5 {
println!("{}", i);
}
break
Use break to exit a loop.
Loop labels
You can label a loop so that break or continue can target a particular loop:
'outer: loop {
loop {
break 'outer;
}
}
continue
Use continue to skip to the next iteration of a loop.
Collections
Collections store multiple values.
Vectors
A vector is a collection that can grow or shrink in size.
Using push and pop
Use push to add a value to a vector and pop to remove a value.
Using a macro
The vec! macro provides a concise way to create a vector, for example vec![1, 2, 3].
Hash maps
A hash map stores key-value pairs.
Declaring a hash map
You can use HashMap from std::collections.
Using insert
Use insert to add a key-value pair to a hash map.
Using get
Use get to retrieve a value by its key.
Structs
A struct is a type that you define yourself.
Declaring a struct
Declare a struct with struct, its name and its fields. For example:
struct Point {
x: i32,
y: i32,
}
Accessing a field
Use a dot to access a struct field, such as point.x.
Creating a constructor with impl
You can define methods and constructor-like functions for a struct using an impl block.
Using modules
You can use modules with structs to organize code.
Modules
Modules help organize code.
Creating a module
Use the mod keyword to declare a module.
Importing a module
Use use to bring a module or item into scope.
Making items public
Use pub to make an item in a module accessible from outside that module.
Traits
A trait is similar to an interface in some other languages and defines behavior that types can provide.
Declaring a trait
Use the trait keyword to declare a trait.
Implementing a trait
You can implement a trait for a struct.
Using a trait
A trait can specify behavior that a struct must provide.
Enums
An enum is a type that can represent several variants.
Declaring an enum
Use the enum keyword to declare an enum.
Using match
Use match to match against an enum value.
Enums with values
Enum variants can also hold values.
Closures
A closure is an anonymous function or lambda.
Declaring a closure
A closure can be written as |parameter| { body }.
Using a closure
You can use a closure much like a function.
Closures as parameters
A function can accept a closure as a parameter.
Want to talk through your finances? Add us on LINE for a free consultation.
Add us on LINE for a free consultation
Or scan the QR code to connect:
