Search code examples
stringrustownership

Is there any use for `str` in Rust?


Is there any case where one would use str without borrowing it? Does that even make sense?

I understand the difference between String and &str, but since there is &str there must also be str?


Solution

  • You can't do much with a value of type str, but there are plenty of cases where you would want to refer to the type str.

    • Box<str> or Rc<str> - owned types, similar to String, but can't be mutated to grow or re-allocate

    • Any time you want to accept an arbitrary type that can be viewed as a string, you could use constraints like T: Deref<Target = str>, T: AsRef<str> or T: Borrow<str>. For example HashMap::get has the following signature:

      pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> where
        K: Borrow<Q>, // K is the key type for the HashMap
        Q: Hash + Eq, 
      

      This means you can have a HashMap<String, i32>, but access values with a &str key, e.g. map.get("key"). Here Q would be inferred to be str, but the k argument would still be a &str (&Q).

      The ?Sized annotation means that Q does not need to have a size known at compile-time, explicitly allowing unsized types like str to be used.