Rust Tutorials: Understanding String vs `str` 🎯

beginner
9 min

Rust Tutorials: Understanding String vs str 🎯

Welcome to our deep dive into the world of Rust! Today, we're going to explore one of the fundamental concepts in Rust: the difference between String and str.

What are String and str? 📝

In Rust, both String and str are used to represent strings. However, they have different purposes and behaviors.

  • String is a growable string that is owned by the Rust heap. It's the most common type for strings and is created using the String::new() function.

  • str (short for "slice of strings") is a slice of characters that is borrowed from somewhere else. It's immutable and has a fixed length.

Creating String and str 💡

Creating a String

Let's create a String:

rust
let my_string = String::from("Hello, World!");

In this example, we create a String named my_string with the text "Hello, World!".

Creating an str

Creating an str is a bit different because it's not an owned type. Instead, you create an str from an existing string:

rust
let my_string = String::from("Hello, World!"); let my_str: &str = "Hello, World!"; // This creates an immutable reference to the string

Here, my_str is an str that points to the same memory location as my_string.

Understanding Ownership 📝

Ownership in Rust is a unique concept that makes Rust stand out. It's crucial to understand ownership when working with String and str.

  • Each value in Rust has a single owner. When the owner goes out of scope, the value is dropped, and its memory is freed.

  • String owns the memory it allocates, so when a String goes out of scope, the memory it allocated is deallocated.

  • str does not own memory, but it points to a region of memory owned by something else.

Using String and str 💡

Using String

Here's an example of using a String:

rust
let my_string = String::from("Hello, World!"); let my_new_string = my_string.replace("World", "Rust"); println!("{}", my_new_string);

In this example, we create a String, replace the text "World" with "Rust", and then print the result.

Using str

Since str is a reference, you can't modify it directly. However, you can create a new String from an str and modify that:

rust
let my_string = String::from("Hello, World!"); let my_str: &str = "Hello, World!"; let my_new_string = String::from(my_str); let my_new_new_string = my_new_string.replace("World", "Rust"); println!("{}", my_new_new_string);

In this example, we create an str from my_string, create a new String, replace the text "World" with "Rust", and then print the result.

Quiz 🎯

Quick Quiz
Question 1 of 1

Which of the following is a mutable `String`?

Wrapping Up ✅

We've covered the basics of String and str in Rust. By understanding ownership and how to create and use these types, you're one step closer to becoming a proficient Rustacean!

Stay tuned for more Rust tutorials on CodeYourCraft! If you have any questions or feedback, feel free to reach out. Happy coding! 🚀