Arrays
| Fixed-size arrays | |
| Indexing | |
| Length | |
| Out of bounds panics |
Fixed-size arrays
An array holds a fixed number of values that all share one type.
List the elements in brackets, or repeat one value with a semicolon count.
fn main() {
let nums = [1, 2, 3];
let zeros = [0; 4];
println!("{:?} {:?}", nums, zeros);
}
cargo run
[1, 2, 3] [0, 0, 0, 0]
Indexing
Read an element by its position in brackets, counting from zero.
Indexes work in expressions too, so values can be printed, copied, or combined directly.
fn main() {
let nums = [10, 20, 30];
println!("{} {}", nums[0], nums[2]);
}
cargo run
10 30
Length
The len method reports how many elements the array holds.
Since the size is fixed at compile time, the result never changes while the program runs.
fn main() {
let nums = [10, 20, 30];
println!("{}", nums.len());
}
cargo run
3
Out of bounds panics
Direct indexing checks the range at run time and panics when the index is outside the array.
Prefer get for risky positions: it returns Some value on success and None when nothing is there.
fn main() {
let nums = [1, 2, 3];
match nums.get(10) {
Some(value) => println!("{}", value),
None => println!("missing"),
}
}
cargo run
missing
Next: Vectors
Article author: Arthur Isaev