OneBite.Dev - Coding blog in a bite size

Slice A String In Rust

Code snippet for how to Slice A String In Rust with sample and detail explanation

In this article, we will delve into how to slice a string in Rust. This vital operation is paramount for various functionalities in string manipulation within Rust, a system programming language that guarantees memory safety.

Code snippet: How to slice a string in Rust

fn main() {
    let s = String::from("Hello, World!");
    let slice = &s[0..5];
    println!("{}", slice);
}

Code Explanation: How to slice a string in Rust

Let’s break down this code piece by piece to better understand how we are able to slice a string in Rust.

  • let s = String::from("Hello, World!");

This line of code simply initializes a new string, “Hello, World!”, and binds it to the variable s.

  • let slice = &s[0..5];

This line is where the actual slicing takes place. The slice is a reference to a section of the original string s, hence the &. The numbers in the brackets ([0..5]) determine which segment of the original string you want to reference. In Rust, these numbers are zero-indexed, which means the first character of the string is at position 0. The range 0..5 gives us a slice of the first five characters.

  • println!("{}", slice);

Finally, this line prints out the slice that was created in the previous line. As we sliced from index 0 to 5, the output would be “Hello”.

In conclusion, slicing a string in Rust involves referencing a specific range of the string in question. The range is known as a slice and we can choose what part of the string to slice by specifying the start and end index within the array-like brackets.

rust