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

前端 未结 9 1013
醉梦人生
醉梦人生 2020-11-22 05:11

Why does Rust have String and str? What are the differences between String and str? When does one use String

9条回答
  •  Happy的楠姐
    2020-11-22 05:59

    std::String is simply a vector of u8. You can find its definition in source code . It's heap-allocated and growable.

    #[derive(PartialOrd, Eq, Ord)]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub struct String {
        vec: Vec,
    }
    

    str is a primitive type, also called string slice. A string slice has fixed size. A literal string like let test = "hello world" has &'static str type. test is a reference to this statically allocated string. &str cannot be modified, for example,

    let mut word = "hello world";
    word[0] = 's';
    word.push('\n');
    

    str does have mutable slice &mut str, for example: pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)

    let mut s = "Per Martin-Löf".to_string();
    {
        let (first, last) = s.split_at_mut(3);
        first.make_ascii_uppercase();
        assert_eq!("PER", first);
        assert_eq!(" Martin-Löf", last);
    }
    assert_eq!("PER Martin-Löf", s);
    

    But a small change to UTF-8 can change its byte length, and a slice cannot reallocate its referent.

提交回复
热议问题