forked from steveklabnik/rust-by-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.rs
More file actions
36 lines (27 loc) · 1.06 KB
/
array.rs
File metadata and controls
36 lines (27 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[int]) {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
}
fn main() {
// Fixed-size array (type signature is superfluous)
let xs: [int, ..5] = [1, 2, 3, 4, 5];
// All elements can be initialized to the same value
let ys: [int, ..500] = [0, ..500];
// Indexing starts at 0
println!("first element of the array: {}", xs[0]);
println!("second element of the array: {}", xs[1]);
// `len` returns the size of the array
println!("array size: {}", xs.len());
// Arrays are stack allocated
println!("array occupies {} bytes", mem::size_of_val(&xs));
// Arrays can be automatically borrowed as slices
println!("borrow the whole array as a slice");
analyze_slice(&xs);
// Slices can point to a section of an array
println!("borrow a section of the array as a slice");
analyze_slice(ys.slice(1, 4));
// Out of bound indexing yields a task failure
println!("{}", xs[5]);
}