DEV Community

Prashant Sharma
Prashant Sharma

Posted on

What are the differences between Rust's `String` and `str`?

When diving into Rust programming, understanding the distinctions between String and str is crucial. Despite their apparent similarity, they serve different purposes and have different characteristics. Let's unravel these differences step by step.

1. What is str?

In Rust, str is an immutable sequence of UTF-8 bytes stored in memory. It represents a string slice, which means it's a view into a string, rather than the string itself. Since str is immutable, you cannot modify the contents of a string slice.

let my_str: &str = "Hello, World!";
Enter fullscreen mode Exit fullscreen mode

2. What is String?

On the other hand, String is a growable, mutable, owned UTF-8 encoded string. It can be dynamically modified and resized as needed, making it more versatile than str.

let my_string: String = String::from("Hello, World!");
Enter fullscreen mode Exit fullscreen mode

3. Ownership and Memory Allocation

One of the key differences between String and str lies in how they handle memory allocation and ownership.

  • String: Owned type. It owns the memory it occupies on the heap. You can freely modify, append, or delete characters from a String, and it will automatically manage the memory for you.

  • str: Borrowed type. It's often used as a reference to a portion of memory owned by another data structure, like String or a string literal. It doesn't own the memory itself, but rather borrows it from another source.

4. Mutability

  • String: Mutable. You can modify the contents of a String after it's been created. For example, you can append characters, remove characters, or change specific characters within the string.

  • str: Immutable. Once a string slice is created, you cannot change its contents. Attempting to modify a str directly will result in a compilation error.

5. Performance Considerations

Since String owns its data and can modify it, it may involve more overhead in terms of memory allocation and deallocation compared to str. If you're working with a fixed, unchanging string, using str can be more memory-efficient.

Conclusion

In summary, understanding the differences between String and str in Rust is essential for writing efficient and safe code. Remember:

  • String is a mutable, growable, and owned string type.
  • str is an immutable string slice type that borrows from another data structure.
  • Consider ownership, mutability, and performance implications when choosing between them in your Rust code.

By grasping these distinctions, you'll be better equipped to leverage Rust's powerful string handling capabilities effectively.

Happy coding!

Top comments (1)

Collapse
 
kapaseker profile image
PangoSea

👏🏻