Rust Function: Print borrowed string
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics