Rust Book Day 2 Flashcards
Learn Rust
what are constants as opposed to immutable variables (7 facts)
- are valid for the entire time a program runs (within the scope declared)
- mut not allowed
- use const keyword instead of let
- type of the value must be annotated
- can also be declared in global scope
- may be set only to a constant expression, not the result of a value that could only be computed at runtime
- capital letters and underscores
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
What is shadowing
declare a new variabled with the same name as a previous variable
fn main() {
let x = 5;
let x = x + 1; { let x = x * 2; println!("The value of x in the inner scope is: {x}"); } println!("The value of x is: {x}"); }
The value of x in the inner scope is: 12
The value of x is: 6 !!!!!
Can we shadow a variable with different type ?
let spaces = “ “;
let spaces = spaces.len();
This is fine even with a different type
let mut spaces = “ “;
spaces = spaces.len();
This is not fine (not shadowing actually)
what is scalar vs compound
scalar type represents a single value
- integers
- floating point numbers
- booleans
- characters
what are signed integers vs unsigned
unsigned can’t be negative
if you use u8 you can go from 0 to 255 where as i8 goes from -128 to 127
how to make 10000 easier to read
10_000
will 255 + 1 wrap when using u8 ?
yes, in –release mode, but not in standard debug mode,
you can use Wrapping(255u8) to make it specific
or wrapping_add method
what are floating point types and are they signed ?
signed, f32 and f64 (default, roughly same CPU speed)
what is result of
let truncated = -5 / 3;
// Results in -1
how is a boolean specified ?
bool
how is a character annotated ?
char
fn main() {
let c = ‘z’;
let z: char = ‘ℤ’; // with explicit type annotation
let heart_eyed_cat = ‘😻’;
}
how to define a tuple and name one fact about them
let my_tup: (i32, f64, u8) = (500, 6.4, 1)
once declared they cannot grow or shrink in size
how to destructure a tuple, name also an alternative “destructuring”
let tup = (500, 6.4, 1);
let (x, y, z) = tup; println!("The value of y is: {y}");
alternatively:
let five_hundred = x.0;
what’s special about arrays in rust?
have fixed length, define it like this:
let a: [i32; 5] = [1, 2, 3, 4, 5];
let a = [3; 5];
// same as
let a = [3, 3, 3, 3, 3];
access it with a[0]
what are statements and expressions
statements are instructions which do not return a value, like let y = 6;
expressions evaluate to a resultant value