What is the difference between str and String in Rust?
I'm still learning and I don't fully understand what each one does or when I should use them.
Could someone explain it in simple terms, ideally with examples?
The type str is the type of actual text — not a container for text, the bytes representing the text itself. It doesn’t say anything about how those bytes got there, just that they are text.
The type &str is the type of a reference to the str — it specifies where in memory the text starts and ends, and can be used to do things like printing the string.
The type String is like &str but it owns the str — it is responsible for managing the allocation of the memory where the str is stored. String is used for a string that’s created at run time, and might be appended to or otherwise modified, because it can make sure to free the memory when it is dropped, and it can create a new larger allocation when the string needs to be longer than fits in the previous memory allocation.
You should use String when you are creating or modifying a string that is not a constant. You should use &str when a function takes text as input. str is rarely mentioned just by itself, because it is a variable-length type, so (loosely speaking) it has to be put in some container that can handle the variable length.
When asking for clarification about Rust concepts, it would certainly help if you could explain what is your current mental model, so that people can identify how much you understand about the concepts and where your mental model falls apart.
Otherwise you risk receiving generic catch-all answers, or even worse, waste people's time.
I have a short article on slice and slice-like types (including str/String) here.