Rust Tutorials: String (growable UTF-8) šŸŽÆ

beginner
25 min

Rust Tutorials: String (growable UTF-8) šŸŽÆ

Welcome to the String (growable UTF-8) tutorial in our Rust series! In this lesson, we'll explore how to work with strings in Rust, focusing on the String type. šŸ“ Note: The String type is the most common way to represent text in Rust and it's UTF-8 encoded.

Understanding the String type šŸ’” Pro Tip:

In Rust, we have several types for representing text. The String type is a growable string that can handle any UTF-8 encoded text. We'll focus on this type in this lesson.

Creating a String šŸŽÆ

To create a String in Rust, you can use the String::new() function or directly use the shorthand "string" syntax.

rust
// Using the `String::new()` function let mut my_string = String::new(); // Using the shorthand syntax let my_other_string = "Hello, World!";

šŸ’” Pro Tip: The mut keyword is used to indicate that a variable can be mutated, or changed, later in the code.

Modifying a String šŸŽÆ

To modify a String, you can use the push_str() function. This function takes a string slice as an argument and appends it to the String.

rust
let my_string = String::from("Hello"); my_string.push_str(", World!"); println!("{}", my_string); // Output: Hello, World!

Splitting a String šŸŽÆ

To split a String into smaller strings, you can use the words() method followed by the collect() method to create a Vec<String>.

rust
let my_string = String::from("This is a test string."); let words: Vec<String> = my_string.words().collect(); println!("{:?}", words); // Output: ["This", "is", "a", "test", "string."]

Quiz šŸŽÆ

Stay tuned for more Rust tutorials! šŸš€