Extract with String Slicing
Write a Rust function that extracts a substring from a &str using Rust's string slicing syntax &s[start..end]. The function takes a string slice and two byte indices, returning the substring between those indices. This demonstrates Rust's approach to string handling with UTF-8 awareness.
Rust strings are UTF-8 encoded, so string indexing is done by byte position, not character index. The slicing syntax &s[start..end] creates a new &str referencing the bytes in the range [start, end). If the byte positions fall within a multi-byte character boundary, the program will panic at runtime. This design choice forces developers to handle UTF-8 boundaries explicitly, preventing invalid string access.
String slices are borrows of the original string data, not copies. They are fat pointers storing both the data pointer and the length. This zero-copy approach makes substring extraction very efficient, as no allocation or copying occurs. The original string data is not modified or consumed.
Time complexity is O(1) as string slicing is a simple pointer and length adjustment. Space complexity is O(1) since the slice borrows existing data without allocation. The slice is valid as long as the original string is alive due to Rust's borrow checker.
Edge cases include slicing from 0 to the full string length (returns the whole string), empty slices (start equals end returns empty string), and ensuring the function does not panic by trusting the caller provides valid byte boundaries.
Example Input & Output
Extract first 5 chars
Whole word
Middle substring
Extract chars 6 to 11
Two chars
Algorithm Flow

Solution Approach
Best Answers
fn solution<'a>(s: &'a str, start: usize, end: usize) -> &'a str {
&s[start..end]
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
