rust string slice
Rust String Slice
In Rust, a string slice is a reference to a portion of a string. It allows you to work with a part of a string without taking ownership of the entire string. String slices are represented by the type &str
in Rust.
To create a string slice, you can use the &
operator followed by the range of indices that represent the desired portion of the string. Here's an example:
fn main() {
let s = "Hello, world!";
let slice = &s[7..12];
println!("{}", slice); // Output: world
}
In the example above, &s[7..12]
creates a string slice that references the characters from index 7 to index 11 (inclusive) of the string s
. The resulting string slice is then printed, which outputs "world".
String slices are useful when you want to work with a part of a string without modifying the original string. They are commonly used as function parameters to avoid unnecessary copying of string data.
Please let me know if you need further assistance!