Understanding the differences between String and str — How to Rust

Ly Channa
2 min readMar 23, 2024

--

In Rust, String and str are two core types that handle string data, but they do so in different ways, catering to different needs in the language's memory safety and management model. Here's a breakdown of their key differences:

String

  • Type: String is a growable, heap-allocated data structure. This means that it can change size at runtime, and it is stored in the heap memory, which allows it to store an amount of text that is unknown at compile time or that might change over time.
  • Ownership: Being a heap-allocated value, a String owns its contents. This plays into Rust's ownership rules, meaning that when a String is moved from one variable to another, the original variable is no longer accessible. This prevents memory safety issues like dangling pointers.
  • Usage: Use String when you need to modify or own your string data, such as appending characters or slicing and altering the string at runtime.

str

  • Type: str, often seen in its borrowed form &str, is an immutable sequence of UTF-8 characters. str itself is a slice ([u8]) and is typically used in its borrowed form, &str, which is a reference to a string slice. It is often referred to as a "string slice".
  • Ownership: Since &str is a reference, it does not own the data it points to. Instead, it borrows it from some other owner (like a String or another &str). This means you can have multiple references to the same string data without copying it, ensuring efficient memory usage and access.
  • Usage: &str is used when you want to access or pass around string data without taking ownership of it. This is common for function parameters that need to read or inspect string data without modifying it.

Key Differences Summarized

  • Memory Allocation: String is stored on the heap and can be resized, whereas str is a fixed-size slice that can live on the stack, in the heap, or in the binary's static memory section (for string literals).
  • Ownership and Borrowing: String follows Rust's ownership rules, while &str is typically used in a borrowing context.
  • Mutability: String can be modified (e.g., appending, removing, changing characters), but str is immutable.

Conversion

It’s common to convert between String and &str:

  • To get a &str from a String, you can use the as_str() method or simply borrow the String with &.
  • To create a String from a &str, you can use the to_string() method or the String::from() function.

Understanding when to use each and how to convert between them is a fundamental part of effective Rust programming, ensuring that you can manage string data efficiently while adhering to the language’s strict memory safety and ownership models.

--

--

Ly Channa
Ly Channa

Written by Ly Channa

Highly skilled: REST API, OAuth2, OpenIDConnect, SSO, TDD, RubyOnRails, CI/CD, Infrastruct as Code, AWS.

No responses yet