w3resource

Rust Ownership, Borrowing, and Lifetimes Exercises with Solutions and Explanations

Rust Ownership, Borrowing, and Lifetimes Exercises [10 exercises with solution and Explanation]

[An editor is available at the bottom of the page to write and execute the scripts. Go to the editor]

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

Click me to see the solution

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

Click me to see the solution

3. Write a Rust function that takes ownership of a vector and returns its length.

Click me to see the solution

4. Write a Rust function that borrows a vector and returns the first element.

Click me to see the solution

5. Write a Rust function that takes ownership of a tuple and returns one of its elements.

Click me to see the solution

6. Write a Rust function that borrows a slice of integers and calculates their sum.

Click me to see the solution

7. Write a Rust function that takes ownership of a string and returns its length.

Click me to see the solution

8. Write a Rust function that borrows a string slice and returns its first character.

Click me to see the solution

9. Write a Rust function that takes ownership of a vector and returns a new vector with a doubled number of elements.

Click me to see the solution

10. Write a Rust function that borrows two integers and returns their sum.

Click me to see the solution

Rust Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



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/ownership-borrowing-and-lifetimes.php