Common Programming Concepts
Constant
- Constants may be set only to a constant expression, not the result of a value that could only be computed at runtime.
Shadowing
- The difference between
mutand shadowing is that the shadowing is in fact creating a new variable when we useletkeyword. So we can change the type of the value but reuse the same name.
Ex. (shadowing)
let spaces = " ";
let spaces =. spaces.len();
Ex. (mut; will cause compile-time error)
let spaces = " ";
spaces = spaces.len();
Data Types
- Scalar
integers, floating-point, Booleans, and chars
- Integers
| Length | Signed | Unsigned |
|---|---|---|
| 8-bit | i8 |
u8 |
| 16-bit | i16 |
u16 |
| 32-bit | i32 |
u32 |
| 64-bit | i64 |
u64 |
| 128-bit | i128 |
u128 |
| Architecture-dependent | isize |
usize |
- Integer Literals
| Number literals | Example |
|---|---|
| Decimal | 98_222 |
| Hex | 0xff |
| Octal | 0o77 |
| Binary | 0b1111_0000 |
Byte (u8 only) |
b'A' |
-
Compound
- Tuple
- Array
-
Tuple
A general way of grouping together a number of values with a variety of types into one compound type with fixed length.
fn main() { let tup: (i32, f64, u8) = (500, 6.4, 1); } fn main() { let tup = (500, 6.4, 1); let (x, y, z) = tup; } -
Array
Array values are allocated on the stack, rather than the heap. Fixed number of elements
let a: [i32; 5] = [1, 2, 3, 4, 5];
let b: [3; 5]; // [3, 3, 3, 3, 3]
Function
The order of function definitions doesn't really matter. Say
fuction1()callsfunction2(). As long asfunction2()can be "seen" byfunction1()within the scope,function2()definition can be written before or afterfuction1()
functions can have `parameters, which are special variables that are part of a function's signature.
Technically, the concrete values for the
parametersare calledarguments
In function signatures, you must declare the type of each
parameter
- Statements are instructions that perform some action and DO NOT RETURN a vaue
- Expressions evaluate to a resultant value
In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function.