rsRustPrimer
< Back to module

Collections

String and &str

Rust has two main text types. String owns its content, on the heap, and can grow. &str is a borrowed view over text, like a slice. String literals in quotes are &str. A simple rule: store String in your structs, take &str as parameters.

rust
fn main() {
let mut label = String::from("ACME");
label.push_str(" Bank");
label.push('!');
let id = 42;
let key = format!("{label}#{id}"); // format! construit une String sans rien consommer
println!("{key}");
let view: &str = &label[..4];
println!("{view}");
}

Strings are always UTF-8. A character can take 1 to 4 bytes, so len() counts bytes rather than characters, and indexing with s[0] does not exist: it could land in the middle of a character. To walk the characters, use chars().

rust
fn main() {
let city = "Zürich";
println!("{} octets, {} caractères", city.len(), city.chars().count()); // 7, 6
// let first = city[0]; // erreur : String cannot be indexed by integer
let first = city.chars().next();
println!("{first:?}");
}

The most useful methods for reading data: trim strips surrounding whitespace, split cuts on a separator, parse turns text into a number. parse can fail ("abc" is not a number), so it returns a Result: we will study it in detail in the next module.

rust
fn main() {
let line = " 7, ACME Bank , 1000000.5 ";
for field in line.split(',') {
println!("[{}]", field.trim());
}
let notional: f64 = "1000000.5".parse().unwrap();
println!("{notional}");
}
unwrap() panics if the conversion fails. Fine in an example, banned in riskforge: we will replace it with real error handling.

Your turn

Write normalize_counterparty, which strips surrounding spaces and uppercases the name, so that " acme bank " and "ACME Bank" refer to the same counterparty.

src/main.rs
fn normalize_counterparty(name: &str) -> String {
todo!()
}
fn main() {
println!("{}", normalize_counterparty(" acme bank ")); // ACME BANK
println!("{}", normalize_counterparty("ACME Bank") == normalize_counterparty(" acme bank ")); // true
}