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
37
38
39
40
|
// ARRAYS - similar than C
//
//array size must be known at compile time
//
// signature: [T; length]
// let var: [T; length] = foo
fn main() {
let arr: [i32; 5] = [1, 2, 3, 4, 5];
// Implicit declaration:
let myarr = ['a', 'b', 'c'];
println!("{}", arr.len());
// Initialize all elements: [value, num of elements]
let auto_arr: [i32; 100] = [1; 100];
for c in arr {
print!("{} ", c);
}
for c in myarr {
print!("{} ", c);
}
println!("");
println!("array sizes: arr {} myarr {}", std::mem::size_of_val(&arr),
std::mem::size_of_val(&myarr));
// Accessing specific elements in an array can be done via indexing or .get method
// .get method returns an Option<T>, so we also need to use unwrap:
let many: [i32; 10] = [1, 3, 4, 6, 8, 34, 60, 44, 94, 10];
// great, either many[3] or &many[3] works, shrug
println!("Via index: {} - Via get method: {}",
&many[3], many.get(6).unwrap());
}
|