String

String is the standard heap-allocated growable UTF-8 string buffer:

  1. fn main() {
  2. let mut s1 = String::new();
  3. s1.push_str("Hello");
  4. println!("s1: len = {}, capacity = {}", s1.len(), s1.capacity());
  5. let mut s2 = String::with_capacity(s1.len() + 1);
  6. s2.push_str(&s1);
  7. s2.push('!');
  8. println!("s2: len = {}, capacity = {}", s2.len(), s2.capacity());
  9. let s3 = String::from("🇨🇭");
  10. println!("s3: len = {}, number of chars = {}", s3.len(),
  11. s3.chars().count());
  12. }

String implements Deref, which means that you can call all str methods on a String.

  • len() returns the size of the String in bytes, not its length in characters.
  • chars() returns an iterator over the actual characters.