DEV Community

Cover image for [Rust Guide] 3.3. Data Types - Compound Types
SomeB1oody
SomeB1oody

Posted on

[Rust Guide] 3.3. Data Types - Compound Types

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
}
Enter fullscreen mode Exit fullscreen mode

Destructuring:

fn main(){
    let tup:(u32,f32,i64) = (6657, 0.0721, 114514);
    let (x, y, z) = tup;
    println!("{},{},{}", x, y, z);
}
Enter fullscreen mode Exit fullscreen mode

Access:

println!("{},{},{}", tup.0, tup.1, tup.2);
Enter fullscreen mode Exit fullscreen mode

3.3.2. Array

Characteristics:

  • Same type elements
  • Fixed length
let a = [1, 1, 4, 5, 1, 4];
Enter fullscreen mode Exit fullscreen mode

Use cases:

  • Stack allocation
  • Fixed size needed
  • Less flexible than Vec

Type:

let machine: [u32;4] = [6, 6, 5, 7];
Enter fullscreen mode Exit fullscreen mode

Initialization:

let a = [3;2];
let b = [3, 3, 3];
Enter fullscreen mode Exit fullscreen mode

Access:

let machine = [6, 6, 5, 7];
let wjq = machine[0];
Enter fullscreen mode Exit fullscreen mode

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];
Enter fullscreen mode Exit fullscreen mode
let a = [1, 9, 10, 4, 5];
let machine = [6, 6, 5, 7];
let wjq = machine[a[4]];
Enter fullscreen mode Exit fullscreen mode

Top comments (0)