Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust - string slices

  • Provide address of bytes, but make sure you are on the character boundaries!
fn main() {
    let text = String::from("The black cat: πŸˆβ€ climbed the green tree: 🌳!");
    println!("{}", text);
    println!("'{}'", &text[4..4]); // ''  empty string
    println!("'{}'", &text[4..=4]); // 'b'
    println!("'{}'", &text[4..9]); // 'black'
    println!("'{}'", &text[30..]); // ' the green tree: 🌳!'
    println!("'{}'", &text[..4]); // 'The '

    println!("'{}'", &text[15..22]); // 'πŸˆβ€'

    //println!("'{}'", &text[16..22]); // panic!: byte index 16 is not a char boundary; it is inside '🐈' (bytes 15..19)

    //println!("'{}'", &text[25..60]);  // panic! at 'byte index 60 is out of bounds
}
The black cat: πŸˆβ€ climbed the green tree: 🌳!
''
'b'
'black'
' the green tree: 🌳!'
'The '
'πŸˆβ€'