w3resource

Rust Function: Printing Owned string

Rust Ownership, Borrowing, and Lifetimes: Exercise-1 with Solution

Write a Rust function that takes ownership of a string and prints it.

Sample Solution:

Rust Code:

// Define a function named 'print_owned_string' that takes ownership of a string and prints it
fn print_owned_string(s: String) {
    println!("Owned string: {}", s);
} // Here 's' goes out of scope and is dropped. Ownership is transferred to the function when called.

fn main() {
    let my_string = String::from("Hello, world!"); // Define a string

    // Call the 'print_owned_string' function and pass the ownership of 'my_string' to it
    print_owned_string(my_string);

    // Error! 'my_string' is no longer accessible here because ownership was transferred to the function
    // println!("Attempt to use 'my_string': {}", my_string);
}

Output:

Owned string: Hello, world!

Explanation:

Here is a brief explanation of the above Rust code:

  • fn print_owned_string(s: String) { ... }: This is a function named "print_owned_string()" that takes ownership of a "String" as input and prints it. The parameter s is of type "String", indicating ownership transfer.
  • Inside the function:
    • We simply print the owned string 's'.
  • In the main function,
    • Define a "String" named 'my_string'.
    • Then call the "print_owned_string()" function and pass the ownership of 'my_string' to it. Ownership of 'my_string' is transferred to the function, and 'my_string' goes out of scope after the function call.
    • Attempting to use 'my_string' after passing ownership to the function will result in a compilation error, as ownership has been moved.

    Rust Code Editor:

    Previous: Rust Ownership, Borrowing, and Lifetimes Exercises.
    Next: Rust Function: Print borrowed string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.