Friday, April 22, 2022

Go vs Rust - Slices

 Slices

Go

Slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. Slice is a variable-length sequence which stores elements of a similar type. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array. Internally, slice and an array are connected with each other, a slice is a reference to an underlying array.

    // Creating a slice using the var keyword
    var my_slice_1 = []string{"Geeks", "for", "Geeks"}
    // Creating an array
    arr := [4]string{"Geeks", "for", "Geeks", "GFG"}
    // Creating slices from the given array
    var my_slice_2 = arr[1:2]
    // Creating slices from the given slice
    var my_slice_3 = my_slice_3[1:5]

Generally, make() function is used to create an empty slice. Here, empty slices are those slices that contain an empty array reference

    // Creating an array of size 7 and slice this array  till 4
    // and return the reference of the slice Using make function
    var my_slice_1 = make([]int, 4, 7)
    fmt.Printf("Slice 1 = %v, \nlength = %d, \ncapacity = %d\n",
                   my_slice_1, len(my_slice_1), cap(my_slice_1))
 
    // Creating another array of size 7 and return the reference of the slice
    // Using make function
    var my_slice_2 = make([]int, 7)
    fmt.Printf("Slice 2 = %v, \nlength = %d, \ncapacity = %d\n",
                   my_slice_2, len(my_slice_2), cap(my_slice_2))

Multi-Dimensional Slice

 // Creating multi-dimensional slice
    s1 := [][]int{{12, 34},
        {56, 47},
        {29, 40},
        {46, 78},
    }
   
 sort.Ints(sl)
sort.IntsAreSorted(sl)

Rust

Slice is a data type that does not have ownership. Slice references a contiguous memory allocation rather than the whole collection. Slice is used when you do not want the complete collection, or you want some part of it. 

fn main() {
    let gfg = "GFG is a great start to start coding and improve".to_string();   
    // for first character
    println!("first character ={}",&gfg[0..1] );   
      // for first three characters
    println!("first three character ={}",&gfg[..3] );
      // calculating length of String
    let length_of_string=gfg.len();   
      let x=5;  
    // start from first to last character
    println!("start from 0 to x ={}",&gfg[..x] ); 
      // start from x to last character
    println!("start from x to end ={}",&gfg[x..length_of_string]);   
      // start from first to last character
    println!("from start to last ={}",&gfg[..length_of_string])
}


lc2)




No comments:

Post a Comment