Rust Function: Take Tuple Ownership, Return element
Rust Ownership, Borrowing, and Lifetimes: Exercise-5 with Solution
Write a Rust function that takes ownership of a tuple and returns one of its elements.
Sample Solution:
Rust Code:
// Define a function named 'get_tuple_element' that takes ownership of a tuple and returns one of its elements
fn get_tuple_element(tuple: (i32, f64, char)) -> char {
let (_, _, c) = tuple; // Destructure the tuple to extract the third element (char)
c // Return the third element of the tuple
} // Here 'tuple' goes out of scope and is dropped. Ownership is transferred to the function when called.
fn main() {
let my_tuple = (10, 3.14, 'A'); // Define a tuple
// Call the 'get_tuple_element' function and pass the ownership of 'my_tuple' to it
let element = get_tuple_element(my_tuple);
// Error! 'my_tuple' is no longer accessible here because ownership was transferred to the function
// println!("Attempt to use 'my_tuple': {:?}", my_tuple);
// Print the element returned by the function
println!("Third element of the tuple: {}", element);
}
Output:
Third element of the tuple: A
Explanation:
Here is a brief explanation of the above Rust code:
- fn get_tuple_element(tuple: (i32, f64, char)) -> char { ... }: This is a function named get_tuple_element that takes ownership of a tuple (i32, f64, char) as input and returns one of its elements (char). The parameter "tuple" is of type (i32, f64, char), indicating ownership transfer.
- Inside the function:
- We destructure the tuple using pattern matching to extract the third element (char).
- We return the third element of the tuple.
- In the main function,
- Define a tuple named 'my_tuple'.
- Then call the "get_tuple_element()" function and pass the ownership of 'my_tuple' to it. Ownership of 'my_tuple' is transferred to the function, and 'my_tuple' goes out of scope after the function call.
- Attempting to use 'my_tuple' after passing ownership to the function will result in a compilation error, as ownership has been moved.
- Finally we print the element returned by the function.
Rust Code Editor:
Previous: Rust Function: Borrow Vector, Get first element.
Next: Rust Function: Calculate Sum of Borrowed integers.
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://w3resource.com/rust/basic/rust-ownership-borrowing-and-lifetimes-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics