Strings
In Chapter 1, Getting Started with Rust, we mentioned that strings are of two types. In this section, we'll give a clearer picture on strings, their peculiarities, and how they differ from strings in other languages.
While other languages have a pretty straightforward story on string types, the String
type in Rust is one of the tricky and uneasy types to handle. As we know, Rust places distinction on whether a value is allocated on the heap or on the stack. Due to that, there are two kinds of strings in Rust: owned strings (String
) and borrowed strings (&str
). Let's explore both of them.
Owned strings – String
The String
type comes from the standard library and is a heap-allocated UTF-8 encoded sequence of bytes. They are simply Vec<u8>
under the hood but have extra methods that are applicable to only strings. They are owned types, which means that a variable that holds a String
value is its owner. You will usually find that String
types can be created in multiple ways, as...