Skip to content

We are working on this site. Want to help? Open an issue or a pull request on GitHub.

Strings

Rust has two string types:

  • Growable, heap-allocated
  • UTF-8 encoded
  • Owned type
  • Fixed-size string slice
  • UTF-8 encoded
  • Reference type
// String
let s1 = String::from("hello");
let s2 = "hello".to_string();

// &str
let s3 = "hello";
let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2;  // s1 has been moved and can no longer be used
let mut s = String::from("hello");
s.push_str(", world!");
s.push('!');
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
let s = String::from("नमस्ते");
for c in s.chars() {
    println!("{}", c);
}

JavaScript has a single string type:

let s1 = "hello";
let s2 = new String("hello");
let s = String::from("hello");
let len = s.len();  // 5
let s = String::from("hello world");
let contains = s.contains("world");  // true
let s = String::from("hello world");
let s2 = s.replace("world", "rust");
let name = "Alice";
let age = 30;
let s = format!("{} is {} years old", name, age);

Rust’s string system provides safety and performance through its two string types.