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?
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!
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.
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).