summaryrefslogtreecommitdiff
path: root/rust/slices.rs
blob: 096fe565e6c490fc2cfb2f341da0aa9d8c8b305a (plain)
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
// SLICES
//
// Contiguous sequence of elements in a collection
// enables us to borrow part of a collection without
// taking ownership of the whole thing
//
// can be created from arrays, vectors, strings and
// any other collection implementing the 'Deref' trait
//
// slices length are not known at compile time
//
// Type signature: &[T]

fn main() {

    let a: [i32; 5] = [36234689, 2, 3, 4, 5];

    // correct way to annotate slice types
    let slice: &[i32] = &a[..4];

    println!("{:?}", slice);

    // Slices are two-words object (occupies 2-words in memory).
    // first word is the data pointer, second is the slice length:
    let s2: &[i32] = &a[..5];

    // If this is a 64-bit machine, this should return 16 bytes.
    // as we have 64-bit words.
    println!("Slice size: {} bytes", std::mem::size_of_val(&s2));

    // Slices are byte indexed, the index '[foo]' is actually a byte
    // number, not member number.
    //
    // ^ I don't think this is correct, but the course made it work
    // with strings, perhaps it is only valid for string type, shrug.
    let s3: &[i32] = &a[0..1];
    let b: i32 = s3[0];
    println!("{:?}", b);
}