Questions And Answers

More Tutorials

What are the differences between Rust's String and str?

String is the dynamic heap string type, it is considered like mutable variable, like Vec: use it when you need to own or modify your string data.

str is an immutable sequence of UTF-8 bytes of dynamic length somewhere in memory. Since the size is unknown, one can only handle it behind a pointer. This means that str most commonly appears as &str: a reference to some UTF-8 data, normally called a "string slice" or just a "slice". A slice is just a view onto some data, and that data can be anywhere.

  • In static storage: a string literal "foo" is a &'static str. The data is hardcoded into the executable and loaded into memory when the program runs.
  • Inside a heap allocated String: String dereferences to a &str view of the String's data.
  • On the stack:


use std::str;
fn main() {
    let x: &[u8] = &[b'a', b'b', b'c'];
    let stack_str: &str = str::from_utf8(x).unwrap();
    println!("x value = {:?}", x);
    println!("stack_str value = {:?}", stack_str);


x value = [97, 98, 99]
stack_str value = "abc"


In this page (written and validated by ) you learned about What are the differences between Rust's String and str? . What's Next? If you are interested in completing Rust tutorial, we encourage you simply to start here: Rust Tutorial.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.