8.7 Slices and Tuples as Parameters and Return Types
Functions in Rust typically pass data by reference rather than by value. Slices and tuples are two common patterns for referencing or grouping data in function parameters and return types.
8.7.1 Slices
A slice (&[T]
or &str
) references a contiguous portion of a collection without taking ownership.
String Slices
fn print_slice(s: &str) { println!("Slice: {}", s); } fn main() { let s = String::from("Hello, world!"); print_slice(&s[7..12]); // "world" print_slice(&s); // entire string print_slice("literal"); // &str literal }
- Returning slices requires careful lifetime handling. You must ensure the referenced data is valid for the duration of use.
Array and Vector Slices
fn sum(slice: &[i32]) -> i32 { slice.iter().sum() } fn main() { let arr = [1, 2, 3, 4, 5]; let v = vec![10, 20, 30, 40, 50]; println!("Sum of arr: {}", sum(&arr)); println!("Sum of v: {}", sum(&v[1..4])); }
8.7.2 Tuples
Tuples group multiple values, possibly of different types.
Using Tuples as Parameters
fn print_point(point: (i32, i32)) { println!("Point is at ({}, {})", point.0, point.1); } fn main() { let p = (10, 20); print_point(p); }
Returning Tuples
fn swap(a: i32, b: i32) -> (i32, i32) { (b, a) } fn main() { let (x, y) = swap(5, 10); println!("x: {}, y: {}", x, y); }