String Methods and Ownership
Introduction to String Methods and Ownership
Hello! Welcome to this lesson on String Methods and Ownership in Rust. In the previous lesson, we explored string data types, including string literals, the String type, references, and string slices. Today, we'll delve deeper into string manipulation by learning various string methods while understanding Rust's unique ownership model. By the end of this lesson, you will have a strong grasp of how to manipulate strings and understand how ownership affects strings in Rust.
String Concatenation: `push_str`
Rust provides multiple ways to concatenate strings. The push_str method adds a string slice to the end of another String. The variable passed into push_str must be a string literal/slice or a reference to a String. Don't forget to declare the String as mutable with mut.
In this example:
- We created a mutable
Stringcalledgreeting. - We used the
push_strmethod to append the string literal" Rust"togreeting. - We created a
Stringcalledworldand concatenated it togreeting
push_str is useful when you want to add a string slice to an existing string.
String Concatenation using `+`
Another way to concatenate strings is by using the + operator. This method is slightly different as it moves ownership of the original string. In addition, the second variable must be a reference.
In this example:
- We created two
Stringvariables,helloandexplorer. - We create a string literal called
rust - We used the
+operator to concatenate these strings intogreeting. - Note that after using the
+operator,hellocannot be used anymore because its ownership has been moved togreeting.
Understanding how ownership works in string concatenation is crucial. The + operator consumes the left operand's ownership, making it unavailable for further use.
