Open In App

Rust – Slices

Slice is a data type that does not have ownership. Slice references a contiguous memory allocation rather than the whole collection. Slices are also present in Python which is similar to slice here in Rust. Slice is used when you do not want the complete collection, or you want some part of it. 

Slicing Key Points :



//gfg is String or Array
&gfg[0..2]  //from 0 to 1 index
&gfg[0..3]  //from 0 to 2 index
//gfg is String or Array
&gfg[..2] //from 0 to 1 index
&gfg[..3] //from 0 to 3 index
//gfg is String or Array
//calculate length using len() method
length_of_string=gfg.len();
//from 0 to last index
&gfg[..lenght_of_string] 
//from 4th element or index=3 to last index
&gfg[3..length_of_string]

Approach Of Example 1 :

Example 1: Slicing of String in Rust






// Rust program for slicing of String
fn main() {
    
      // String
    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])
}

Output :

first character =G
first three character =GFG
start from 0 to x =GFG i
start from x to end =s a great start to start coding and improve
from start to last =GFG is a great start to start coding and improve

Approach Of Example 2:

Example 2: Slicing the Array




// Rust program for slicing Array
fn main() {
    
    let gfg = [10, 22, 31, 43, 57];
    let length_of_array=gfg.len();
    let x=2;
    
      // for first value
    println!("for first= {:?}",&gfg[0..1]);
    
      // for first three value
    println!("for first three= {:?}",&gfg[0..3]);
    
      // for first to last(or length)
    println!("for 0 to length of the array= {:?}",&gfg[0..length_of_array] );
   
    println!("{:?}",&gfg[x..length_of_array]);
}

Output :

for first= [10]
for first three= [10, 22, 31]
for 0 to length of the array= [10, 22, 31, 43, 57]
[31, 43, 57]

Article Tags :