Rust - Compound Types
In Rust, compound types allow you to group multiple values into a single type. The two primary compound types in Rust are tuples and arrays. These types enable you to work with multiple values simultaneously, providing a way to organize and manage data effectively.
1. Tuples
A tuple is a fixed-size collection of values of potentially different types. Tuples are useful for grouping a small number of related values.
Creating and Accessing Tuples
rustfn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1); // Creating a tuple
let (x, y, z) = tup; // Destructuring the tuple
println!("The value of y is: {}", y);
// Accessing tuple elements by index
println!("The value of x is: {}", tup.0);
println!("The value of z is: {}", tup.2);
}
- Destructuring: You can unpack a tuple into individual variables.
- Indexing: Access elements directly using dot notation with an index.
Returning Tuples from Functions
Tuples are often used to return multiple values from a function.
rustfn main() {
let result = calculate(5, 10);
println!("Sum: {}, Product: {}", result.0, result.1);
}
fn calculate(a: i32, b: i32) -> (i32, i32) {
(a + b, a * b)
}
- Multiple Return Values: Tuples allow you to return more than one value from a function.
2. Arrays
An array is a fixed-size collection of elements of the same type. Arrays are useful when you need to store a fixed number of items of the same type.
Creating and Accessing Arrays
rustfn main() {
let arr = [1, 2, 3, 4, 5]; // Creating an array
println!("The first element is: {}", arr[0]);
println!("The second element is: {}", arr[1]);
// Array with specified type and length
let arr: [i32; 5] = [1, 2, 3, 4, 5];
// Array with the same value repeated
let repeated_arr = [3; 5]; // Equivalent to [3, 3, 3, 3, 3]
}
- Fixed Length: The length of an array is known at compile time and cannot be changed.
- Access by Index: Elements are accessed using index notation
arr[index]
.
Out-of-Bounds Indexing
Rust enforces safety by checking for out-of-bounds access at runtime, which will result in a panic if attempted.
rustfn main() {
let arr = [1, 2, 3, 4, 5];
let index = 10;
// This will panic because the index is out of bounds
let element = arr[index];
println!("The element is: {}", element);
}
Arrays and Slices
You can create a slice from an array, which is a reference to a contiguous sequence of elements in the array.
rustfn main() {
let arr = [1, 2, 3, 4, 5];
let slice = &arr[1..3]; // Slice containing elements 2 and 3
println!("Slice: {:?}", slice);
}
- Slices: Slices are references to a portion of an array or vector and are useful when you need to work with parts of a collection without copying data.
3. Vectors
Although not a strict compound type like tuples or arrays, vectors (Vec
)
are an important collection type in Rust. Unlike arrays, vectors are growable and more flexible.
Creating and Using Vectors
rustfn main() {
let mut vec = Vec::new(); // Create an empty vector
vec.push(1);
vec.push(2);
vec.push(3);
println!("Vector: {:?}", vec);
// Accessing elements
let first = vec[0];
println!("First element: {}", first);
}
- Dynamic Size: Vectors can grow or shrink in size dynamically at runtime.
- Similar to Arrays: They provide similar indexing and slicing capabilities.
Summary
- Tuples: Fixed-size, can hold multiple types, useful for grouping related values.
- Arrays: Fixed-size, hold elements of the same type, useful for collections with a known size.
- Vectors: Dynamic-size, hold elements of the same type, useful for collections that can grow or shrink.
These compound types are foundational in Rust, providing flexibility and safety when working with multiple values in your programs.