rust / intermediate
Snippet
Slices and String Slice Basics
String slices (&str) are a borrowed reference to a sequence of UTF-8 bytes. They can point to part of a String or directly to string literal data in the binary. Using &str in function signatures allows your functions to accept both owned Strings and borrowed string slices without modification.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fn first_word(s: &str) -> &str {let bytes = s.as_bytes();for (i, &byte) in bytes.iter().enumerate() {if byte == b' ' {return &s[0..i];}}s}fn main() {let text = String::from("Hello Rustaceans");let word = first_word(&text);println!("First word: {}", word);let literal = "Hello OpenCode";let word2 = first_word(literal);println!("First word: {}", word2);}
Breakdown
1
fn first_word(s: &str) -> &str
Accepts both &String and &str due to Deref coercion
2
let bytes = s.as_bytes();
Converts string to byte array for byte-level iteration
3
for (i, &byte) in bytes.iter().enumerate()
Iterates with index using enumerate
4
if byte == b' '
Checks for space character using byte literal b' '
5
return &s[0..i]
Returns slice from start to space position