w3resource

Rust Function: Print borrowed string

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

Write a Rust function that borrows a string and prints it.

Sample Solution:

Rust Code:

// Define a function named 'print_borrowed_string' that borrows a string slice and prints it
fn print_borrowed_string(s: &str) {
    println!("Borrowed string: {}", s);
} // Here 's' borrows the string slice. It doesn't go out of scope here.

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

    // Call the 'print_borrowed_string' function and pass a reference to 'my_string' to borrow it
    print_borrowed_string(&my_string);

    // 'my_string' is still accessible here because we only borrowed it
    println!("Used 'my_string' after borrowing: {}", my_string);
}

Output:

Borrowed string: Hello, world!
Used 'my_string' after borrowing: Hello, world!

Explanation:

Here is a brief explanation of the above Rust code:

  • fn print_borrowed_string(s: &str) { ... }: This is a function named "print_borrowed_string()" that borrows a string slice ('&str') and prints it. The parameter 's' is of type '&str', indicating borrowing.
  • Inside the function:
    • We simply print the borrowed string 's'.
  • In the main function:
    • Define a "String" named 'my_string'.
    • Call the "print_borrowed_string()" function and pass a reference to "my_string (&my_string)" to borrow it. Borrowing allows the function to access 'my_string' without taking ownership.
    • After the function call, we're still able to use 'my_string' because it was only borrowed and not moved.

Rust Code Editor:

Previous: Rust Function: Printing Owned string.
Next: Rust Function: Getting Vector length.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/basic/rust-ownership-borrowing-and-lifetimes-exercise-2.php