3.3.0. Before the Main Text
Welcome to Chapter 3 of your Rust self-study. There are 6 sections in total:
- Variables and Mutability
- Data Types: Scalar Types
- Data Types: Compound Types (this article)
- Functions and Comments
- Control Flow:
if else - Control Flow: Loops
Through the mini-game in Chapter 2 (strongly recommended for beginners who haven't read it), you should already have learned basic Rust syntax. In Chapter 3, we will go deeper into general programming concepts in Rust.
3.3.1. Introduction to Compound Types
- Compound types group multiple values into one type
- Rust provides: Tuple and Array
3.3.1. Tuple
Characteristics:
- Can hold multiple values of different types
- Fixed length
fn main(){
let tup:(u32,f32,i64) = (6657, 0.0721, 114514);
println!("{},{},{}",tup.0,tup.1,tup.2);
// Output: 6657,0.0721,114514
}
Destructuring:
fn main(){
let tup:(u32,f32,i64) = (6657, 0.0721, 114514);
let (x, y, z) = tup;
println!("{},{},{}", x, y, z);
}
Access:
println!("{},{},{}", tup.0, tup.1, tup.2);
3.3.2. Array
Characteristics:
- Same type elements
- Fixed length
let a = [1, 1, 4, 5, 1, 4];
Use cases:
- Stack allocation
- Fixed size needed
- Less flexible than
Vec
Type:
let machine: [u32;4] = [6, 6, 5, 7];
Initialization:
let a = [3;2];
let b = [3, 3, 3];
Access:
let machine = [6, 6, 5, 7];
let wjq = machine[0];
Out-of-bounds:
- Compile-time or runtime error
- Rust enforces bounds checking
Memory model:
- Continuous memory layout
Comparison:
| Feature | C | C++ | Rust |
|---|---|---|---|
| Memory model | Continuous | Continuous | Continuous |
| Safety | No bounds check |
std::array has checks, raw arrays do not |
Enforced bounds check |
| Dynamic array | Manual memory | std::vector |
Vec |
| Multi-dimensional | Yes | Yes | Yes |
| Special features | Simple | Rich STL | Ownership & borrowing |
Example:
let a = 5;
let machine = [6, 6, 5, 7];
let wjq = machine[a];
let a = [1, 9, 10, 4, 5];
let machine = [6, 6, 5, 7];
let wjq = machine[a[4]];
Top comments (0)