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.

fn main() {
    let mut greeting = String::from("Hello");
    let rust = " Rust";
    greeting.push_str(rust);
    println!("{}", greeting); // Prints: Hello Rust

    let world = String::from(" World!");
    greeting.push_str(&world);
    println!("{}", greeting); // Prints: Hello Rust World!
}

In this example:

  • We created a mutable String called greeting.
  • We used the push_str method to append the string literal" Rust" to greeting.
  • We created a String called world and concatenated it to greeting

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.

fn main() {
    let hello = String::from("Hello, ");
    let rust = "Rust ";
    let explorer = String::from("Explorer!");
    let greeting = hello + &rust + &explorer;
    println!("{}", greeting); // Prints: Hello, Rust Explorer!
    // println!("{}", hello); // Error: `hello` no longer owns "Hello, "
}

In this example:

  • We created two String variables, hello and explorer.
  • We create a string literal called rust
  • We used the + operator to concatenate these strings into greeting.
  • Note that after using the + operator, hello cannot be used anymore because its ownership has been moved to greeting.

Understanding how ownership works in string concatenation is crucial. The + operator consumes the left operand's ownership, making it unavailable for further use.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal