String, str, &String, &str

So, I am working through the Rust Programming Language, google, chatGPT, and still think I understand about 70% here:

The String type is for variables with a string that can mutate, grow and shrink.
The &str type is a literal, but really a slice
The &String type is a reference to a String
The str type I haven’t found yet

So I feel I am missing something still. Why the two types, and the two references, when in the end it is all about strings or references to strings?

&str is not analogous to a slice. str is a string slice, so &str is a reference to a string slice.

ah, there you go. So, why would one use a reference to a slice [..] or a reference to a String? I do think I kind of understand it, but I want to make sure I fully understand it, so my apologies if I am asking the stupid questions here!

1 Like

str is what is known as a DST (Dynamically Sized Type) or "Unsized" type (you might want to research about the Sized trait if you want to know more on the subject). In order to store a variable, the compiler needs to know how much memory it needs for it; by definition, this task is not possible with DSTs, so we need to put them behind a pointer (&, Rc, Arc, etc.) so that the compiler uses the size of the pointer instead.

As for &String, as a rule of thumb you can consider it an anti-pattern. Its use cases are so scarce that in 99% of the cases it's most likely that the user wanted a &str instead, so much so that the compiler can auto dereference the former into the latter.

4 Likes

Thank you, I think I get it!

No. String literals have type &'static str, but not all &strs are literals.

4 Likes

Here's a recent post summarizing slices (including str), and another diagraming the difference between &Vec<_> and &[_] (which is the same as the difference between &String and &str).

This post is a repost from another recent thread :slight_smile:.

5 Likes

My favourite beginner article about strings, cleverly disguised as being about Fizz-Buzz:

https://chrismorgan.info/blog/rust-fizzbuzz/

3 Likes

This is very helpful!

1 Like