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

前端 未结 9 1014
醉梦人生
醉梦人生 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条回答
  •  不知归路
    2020-11-22 06:01

    Here is a quick and easy explanation.

    String - A growable, ownable heap-allocated data structure. It can be coerced to a &str.

    str - is (now, as Rust evolves) mutable, fixed-length string that lives on the heap or in the binary. You can only interact with str as a borrowed type via a string slice view, such as &str.

    Usage considerations:

    Prefer String if you want to own or mutate a string - such as passing the string to another thread, etc.

    Prefer &str if you want to have a read-only view of a string.

提交回复
热议问题