Sub topic 2
Tuple Traits and Fixed-Size Arrays
Assume basic Rust syntax, scalar types, references, borrowing, and running Cargo programs. This chapter focuses on traits that make tuples useful and on common operations for fixed-size arrays.
What tuples can do
A tuple can contain values of different types. Tuples automatically implement several traits when all their elements implement the same traits:
Debugallowsprintln!("{:?}", value).PartialEqallows==and!=.Ordallows ordering and comparisons such as<.Defaultcreates default values for every element.Copyallows cheap copying when every element isCopy.
Trait support depends on the elements. For example, (i32, bool) is Copy, but a tuple containing a String is not.
Arrays: fixed-length sequences
An array stores values of one type. Its length is part of its type, so [i32; 3] and [i32; 4] are different types.
fn main() {
let pair = (3, 4);
let other = (3, 4);
println!("{:?}", pair);
println!("{}", pair == other);
println!("{}", pair < (4, 0));
let defaults: (i32, bool) = Default::default();
println!("{defaults:?}");
let numbers: [i32; 3] = [10, 20, 30];
let repeated = [7; 4];
println!("{} {}", numbers.len(), repeated.len());
println!("{}", numbers[1]);
println!("{:?}", numbers.get(10));
for number in &numbers {
print!("{number} ");
}
println!();
for number in numbers {
print!("{number} ");
}
println!();
let doubled = [1, 2, 3].map(|number| number * 2);
println!("{doubled:?}");
println!("{}", doubled.contains(&4));
}The expression [7; 4] creates an array with four copies of 7. The repeated value must support the required copying behavior. Use an explicit list when that restriction does not fit the element type.
Indexing, iteration, and methods
Indexing with array[index] panics if the index is out of bounds. Use .get(index) when invalid input is expected. It returns Some(&value) or None.
Iterating over &array borrows each element. Iterating over array moves each element out of the array. This is harmless for Copy elements but consumes an array containing non-Copy values.
Common array methods include len, is_empty, contains, first, last, get, and map.
Exercise
What does [0u8; 8] create, and what happens when get(20) is called on it?
Show answer
It creates an eight-element byte array. get(20) returns None instead of panicking.