Chapter 2
Chapter 2
* immutable by default
- but we can make the mutable if we want, by mut keyword
Constants
- always immutable, can't use mut
- const keyword, type must be declared
- can be declared in global scope
- can only be set up to a const expression, not a value computed at runtime
- valid for entire program
Shadowing
- declaring a new variable with the same name as the previous one
- goes on until the variable itself is shadowed / the scope ends
- allows changing type (can't with mut)
-------------------------------------------------------
Data Types
Scalar Types
- represent a single value
Integer:
- number without fractional part
u: unsigned
i: signed (based on Two’s Complement encoding)
i8, u8, i16, u16, i32, u32, i64, u64, i128, u128, isize, usize (arch)
default: i32
Integer literals
- decimal: 98_222
- hex: 0xff
- octal: 0o77
- binary: 0b1111_0000
- byte (u8 only): b’A’
integer overflow
- debug mode: panic
- release mode: two’s complement wrapping
Floating-point numbers
- numbers with fractional part
f32, f64
default: f64
Booleans
- true, false
- 1 byte size
Chars
- single quotes ‘’
- 4 bytes in size, represents Unicode scalar value
Compound Types
- group multiple values into one type
Tuples
- groups multiple values of various types into one compound type
- have fixed size (can’t grow or shrink)
- each element has a type
Arrays
------------------------------------------------------------
Functions
function declaration: order does not matter as long as defined in a scope seen by
caller
Statements: instructions that perform an action and do not return a value (return
())
Expressions: instructions that evaluate to a resultant value
statement examples
- declaring functions, declaring variables (different from C)
* can’t write x = y = 6
expression examples
- 5 + 6
- 6
- calling functions: returns a value or ()
- calling macros: returns ()
- a new scope created with {}: evaluates to last expression in it;
Return values
- must declare type with arrow (→)
* fn main() → type
- consist of expressions
- can use “return” to return early
Comments
Control Flow
Loops
Loop labels
- loops can be attached with labels which can be used with break and continues
→ break and continue will apply to specified loop instead of innermost loop.
‘label: loop {}
break ‘label;
continue ‘label;
while condition { }
for element in a { }