There are two "mainly used" string types in Rust. The str slice, which is mostly seen as a borrowed &str slice. And the errm ... String. Wait ... Wut?

rust
// Create a `borrowed string`.
let stuff = "stuff";

// Create a `borrowed string` and annotate the type.
let stuff: &str = "stuff";

// Create a `String`.
let things = "things".to_string();
let things = String::from("things");

// Create a `String` and annotate the type.
let things: String = "things".to_string();
let things: String = String::from("things");

String Considerations

  • The data in a borrowed &str slice CANNOT be modified.
  • The data in a String CAN be modified.
  • A &str has a static lifetime and is guaranteed to be valid for the duration of the entire program
  • A &str is made up of a ptr to some bytes and a length.
  • A String is made up of a ptr to some bytes and a length and a capacity that may be larger than the length.
  • Both &str and String are valid UTF-8.

Tags

rust