Rust Function: Borrow Slice, Calculate Sum
Rust Ownership, Borrowing, and Lifetimes: Exercise-7 with Solution
Write a Rust function that takes ownership of a string and returns its length.
Sample Solution:
Rust Code:
// Define a function named 'get_string_length' that takes ownership of a string and returns its length
fn get_string_length(s: String) -> usize {
s.len() // Return the length of the string
} // 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 'get_string_length' function and pass the ownership of 'my_string' to it
let length = get_string_length(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);
// Print the length of the string returned by the function
println!("Length of the string: {}", length);
}
Output:
Length of the string: 13
Explanation:
Here is a brief explanation of the above Rust code:
- fn get_string_length(s: String) -> usize { ... }: This is a function named "get_string_length()" that takes ownership of a 'String' as input and returns its length as a 'usize'. The parameter 's' is of type 'String', indicating ownership transfer.
- Inside the function:
- We use the "len()" method to get the length of the string 's'.
- We return the length of the string.
- In the main function,
- Define a "String" named 'my_string'.
- We then call the "get_string_length()" 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.
- Finally print the length of the string returned by the function.
Rust Code Editor:
Previous: Rust Function: Calculate Sum of Borrowed integers.
Next: Rust Function: Borrow String Slice, Get first character.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics