Code Logo

Extract with String Slicing

Published at25 Jul 2026
Rust String Handling Medium 0 views
Like0

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

Example 1
Input
"hello world",0,5
Output
"hello"
Explanation

Extract first 5 chars

Example 2
Input
"rust",0,4
Output
"rust"
Explanation

Whole word

Example 3
Input
"abcdef",2,4
Output
"cd"
Explanation

Middle substring

Example 4
Input
"hello world",6,11
Output
"world"
Explanation

Extract chars 6 to 11

Example 5
Input
"hi",0,2
Output
"hi"
Explanation

Two chars

Algorithm Flow

Recommendation Algorithm Flow for Extract with String Slicing
Recommendation Algorithm Flow for Extract with String Slicing

Solution Approach

fn solution(s: &str, start: usize, end: usize) -> &str {
    &s[start..end]
}

Best Answers

rust - Approach 1
fn solution<'a>(s: &'a str, start: usize, end: usize) -> &'a str {
    &s[start..end]
}