Building block of Rust language

Building block of Rust language

(Arrays & Slices)

⚡ arrays : data type and size of array is in advance because it is a step forward concept
let xs: [data_type; size] = [...elements_comma_seperated]
let ejaz: [i32; 2] = [50, 100, 30] ;

⚡ len() : common function returns the size of an array
let array_size = xs.len();

⚡ slices : magic of array that is part of an array can passed, how ?
let slice: &[i32] = &xs[1..2] // slice will have [100, 300]

main.rs

fn main() {
  let x:[i32; 3] = [1, 2, 3]; //immutable

  // we can create many as such , immutable array can borrow as many mutable slices as we want ? yes
  let slice =  &x[0..2];
  let slice1 = &x[1..2];

  // immutable array cannot borrow the slice of mutable ? yup
  //let slice2 = &mut x[0..2]; 

  /*
  Not exactly: You could make `x` mutable with
  `let mut x = [1,2,3];` 
  then `let slice2 = &mut x[0..2]` would work.
  However, 
  you cannot borrow both `slice2` and `slice` or `slice1` 
  at the same time.

  */

  /*  
  Yes. `slice` and `slice1` can be used at the same time without limitation. 
  `slice2` would need making `x` mutable
  (because you cannot borrow an immutable value mutably),
    and as it represents a mutable borrow, 
    you could not have any further uses of `slice` nor `slice1` 
    in this scope as long as `slice2` is alive.
  */
}

main.rs

fn main() {

    //bit new way of initializing array 
    let xs: [i32; 4] = [5,10,40,4];
    
    //simple function to count total no. of elements
    let size = xs.len();
    
    println!("first element of the array: {} & no. elements {}", xs[0], size);

    //Awesome!!, do you get it ?? Yup it is looking weird but
    //Trust me it is awesome
    // we just sliced the part of array from index 1 to 3 (so slices will have [10,40] not 0) 
    let slice: &[i32] = &xs[1..3];
    println!("first element of the array: {}", slice[1]);
    
    //slice[0] = 10; //This is not allowed, you cannot change the value of slice
}


Note: Slices are just a references, it is slice of an array. Slices values change or modify result into an error

Wow I totally enjoyed todays learning, it was totally new. Feel free to join me and we can have fun together.

 

Ejaz Shaikh

I'm passionate about freelancing, technology and healthy lifestyle. I enjoy writing code and writing about code.

Something awesome will come here..