MCPcopy Create free account
hub / github.com/ahgamut/rust-ape-example / part0

Function part0

src/bin/primitives_array.rs:12–58  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

10}
11
12fn part0() {
13 // Fixed-size array (type signature is superfluous)
14 let xs: [i32; 5] = [1, 2, 3, 4, 5];
15
16 // All elements can be initialized to the same value
17 let ys: [i32; 500] = [0; 500];
18
19 // Indexing starts at 0
20 println!("first element of the array: {}", xs[0]);
21 println!("second element of the array: {}", xs[1]);
22
23 // `len` returns the count of elements in the array
24 println!("number of elements in array: {}", xs.len());
25
26 // Arrays are stack allocated
27 println!("array occupies {} bytes", mem::size_of_val(&xs));
28
29 // Arrays can be automatically borrowed as slices
30 println!("borrow the whole array as a slice");
31 analyze_slice(&xs);
32
33 // Slices can point to a section of an array
34 // They are of the form [starting_index..ending_index]
35 // starting_index is the first position in the slice
36 // ending_index is one more than the last position in the slice
37 println!("borrow a section of the array as a slice");
38 analyze_slice(&ys[1 .. 4]);
39
40 // Example of empty slice `&[]`
41 let empty_array: [u32; 0] = [];
42 assert_eq!(&empty_array, &[]);
43 assert_eq!(&empty_array, &[][..]); // same but more verbose
44
45 // Arrays can be safely accessed using `.get`, which returns an
46 // `Option`. This can be matched as shown below, or used with
47 // `.expect()` if you would like the program to exit with a nice
48 // message instead of happily continue.
49 for i in 0..xs.len() + 1 { // OOPS, one element too far
50 match xs.get(i) {
51 Some(xval) => println!("{}: {}", i, xval),
52 None => println!("Slow down! {} is too far!", i),
53 }
54 }
55
56 // Out of bound indexing causes compile error
57 //println!("{}", xs[5]);
58}
59
60pub fn main() {
61 part0();

Callers 1

mainFunction · 0.70

Calls 3

analyze_sliceFunction · 0.85
lenMethod · 0.80
getMethod · 0.80

Tested by

no test coverage detected