Rs
Module 2Slices & ViewsLesson 7 of 920 min

String Slices (&str)

Views into string data — parsing symbols and message prefixes without copy.

Slices are views

rust
let s = String::from("AAPL.O");
let root = &s[0..4]; // "AAPL" — careful: must be byte boundaries

Prefer safe APIs:

rust
fn main() {
    let sym = "MSFT";
    assert!(sym.starts_with("MS"));
    for part in "A,B,C".split(',') {
        println!("{part}");
    }
}
Output
A
B
C

API rule of thumb

Take &str in functions so both literals and String work (String coerces to &str).

Exercise

Parse "SYM:QTY" style tags.

Challenge

Return Option<(&str, f64)> instead of dummy defaults.

Tips
  • Byte indexing can panic on non-UTF8 boundaries — prefer APIs
  • &str is the flexible borrowed string type
  • split returns an iterator of &str

Try it live

String Slices (&str)Rust 2021
Loading editor…
Output
Press Run to compile and execute.