DEV Community

BC
BC

Posted on

Day2:Tuple,Array - 100DayOfRust

Tuple, Array and Slice

use std::mem;

fn calculate(a: i32, b:i32) -> (i32, i32) {
    (a + b, a - b)
}

fn stat_slice(slice: &[i32]) {
    println!("Slice has length: {}", slice.len());
}

fn main() {
    // unpacking to assign
    let (a, b) = (5, 3);
    // get the returned tuple
    let (a, b) = calculate(a, b);
    println!("a is {}, b is {}", a, b);

    // array
    let a:[i32; 5] = [1, 2, 3, 4, 5];
    for num in a.iter() {
        println!("num is {}", num);
    }
    println!("First num is {}", a[0]);
    println!("Size of A is {} bytes", mem::size_of_val(&a));

    // slice
    stat_slice(&a);
    stat_slice(&a[2..4]);
}
Enter fullscreen mode Exit fullscreen mode

Result:

a is 8, b is 2
num is 1
num is 2
num is 3
num is 4
num is 5
First num is 1
Size of A is 20 bytes
Slice has length: 5
Slice has length: 2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)