Performant Software Systems with Rust — Lecture 3
Mutable and immutable variables
Variables are immutable by default — you are allowed to bind a value to an immutable variable only once
Learn more: Variables and Mutability
Learn more: Variables and Mutability
Naming convention: all upper case with underscores
const
: a constant value that can be completely computed at compile time
any code that refers to them is replaced with the constant’s computed value at compile time
Just a convenient name for a particular value
static
: global variable (may only be modified with unsafe
)
Both constants and globals need explicit type annotation
Learn more: Constants
Contants
Learn more: Constants
Learn more: Constants
{ }
Learn more: Scope and Shadowing
Shadowing in the Guessing Game
Learn more: Scope and Shadowing
Rust is a statically typed language — the compiler must know the types of all variables at compile-time
Rust vs. Javascript
Rust
But what if we wish to add two floating-point numbers?
Rust vs. Python — Rust
Rust vs. Python — Python
Rust vs. Javascript — Javascript
Length | Signed | Unsigned |
---|---|---|
32-bit | i32 |
u32 |
arch-dep | isize |
usize |
Learn more: Data Types
Length | Type |
---|---|
32-bit | f32 |
64-bit | f64 |
Learn more: Data Types
Numeric Operations
Learn more: All Operators in Rust
Learn more: Data Types
Learn more: Data Types
The Tuple Type
Groups together some values with a variety of types
Once declared, cannot grow or shrink in size
Useful when a function needs to return multiple values
Learn more: Data Types
Learn more: Data Types
Learn more: Data Types
()
Learn more: Data Types
The Array Type
Learn more: Data Types
Functions
->
(the unit type ()
is the default)Learn more: Functions
Functions
Learn more: Functions
if
ExpressionsLearn more: Control Flow
Control Flow — if
Expressions
Learn more: Control Flow
let big_n =
if n < 10 && n > -10 {
println!(", and is a small number, increase ten-fold");
// This expression returns an `i32`
10 * n
} else {
println!(", and is a big number, halve the number");
// This expression must return an `i32` as well
n / 2 // Try suppressing this expression with a semicolon
}; // Don't forget to put a semicolon here
println!("{} -> {}", n, big_n);
}
Learn more: Control Flow
Repetition with Loops — loop
A loop
loop can return a value with the break
keyword
Learn more: Loops
Repetition with Loops — while
A while
loop is just like C, minus the parentheses
Learn more: Loops
Repetition with Loops — for
Learn more: Loops
The Rust Programming Language, Chapter 3