Slices are references to a contiguous sequence of elements - they don't own the data.
&strlet s = String::from("hello world");
let hello = &s[0..5]; // "hello"
let world = &s[6..11]; // "world"
// Shorthand:
let hello = &s[..5]; // from start
let world = &s[6..]; // to end
let full = &s[..]; // entire stringString literals are already slices: let s: &str = "hello";
&[T]let arr = [1, 2, 3, 4, 5];
let slice: &[i32] = &arr[1..4]; // [2, 3, 4]Account data in Solana is accessed as byte slices (&[u8]). Understanding slices is essential!
Implement first_word that returns the first word in a string (up to the first space).
&str slice of the input"hello world" → "hello"// Iterate with index
for (i, c) in s.chars().enumerate() {
if c == ' ' {
return &s[..i];
}
}.chars() to iterate over characters.enumerate() to get indices&s[..index] to slice from start&s[..] or just s to return the whole string