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.
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.
String šÆTo create a String in Rust, you can use the String::new() function or directly use the shorthand "string" syntax.
// 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.
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.
let my_string = String::from("Hello");
my_string.push_str(", World!");
println!("{}", my_string); // Output: Hello, World!String šÆTo split a String into smaller strings, you can use the words() method followed by the collect() method to create a Vec<String>.
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."]Stay tuned for more Rust tutorials! š