Table of contents
Introduction:
Ownership and borrowing are fundamental concepts in Rust that ensure memory safety and prevent common pitfalls like data races and dangling pointers. To solidify your understanding of these concepts, it's crucial to practice them through exercises. In this article, we will provide a series of exercises to help you reinforce your knowledge of ownership and borrowing in Rust.
Exercise 1: Swap Values Write a function that takes two mutable references to integers and swaps their values.
fn swap_values(a: &mut i32, b: &mut i32) {
let temp = *a;
*a = *b;
*b = temp;
}
fn main() {
let mut x = 5;
let mut y = 10;
swap_values(&mut x, &mut y);
println!("x: {}, y: {}", x, y); // Output: x: 10, y: 5
}
Exercise 2: Calculate Average Write a function that takes a slice of integers and returns the average of the numbers.
fn calculate_average(numbers: &[i32]) -> f64 {
let sum: i32 = numbers.iter().sum();
let count = numbers.len() as f64;
f64::from(sum) / count
}
fn main() {
let numbers = [5, 10, 15, 20, 25];
let average = calculate_average(&numbers);
println!("Average: {:.2}", average); // Output: Average: 15.00
}
Exercise 3: Find Maximum Write a function that takes a slice of integers and returns the maximum value.
fn find_maximum(numbers: &[i32]) -> Option<i32> {
numbers.iter().max().cloned()
}
fn main() {
let numbers = [5, 10, 15, 20, 25];
match find_maximum(&numbers) {
Some(max) => println!("Maximum: {}", max), // Output: Maximum: 25
None => println!("No numbers found."),
}
}
Exercise 4: Count Vowels Write a function that takes a string slice and returns the count of vowels in the string.
fn count_vowels(string: &str) -> usize {
string
.chars()
.filter(|c| "aeiouAEIOU".contains(*c))
.count()
}
fn main() {
let text = "Hello, World!";
let vowel_count = count_vowels(&text);
println!("Vowel Count: {}", vowel_count); // Output: Vowel Count: 3
}
Exercise 5: Concatenate Strings Write a function that concatenates two string slices and returns a new String
.
fn concatenate_strings(a: &str, b: &str) -> String {
let result = format!("{}{}", a, b);
result
}
fn main() {
let first_name = "John";
let last_name = "Doe";
let full_name = concatenate_strings(&first_name, &last_name);
println!("Full Name: {}", full_name); // Output: Full Name: JohnDoe
}
Conclusion:
Practicing ownership and borrowing concepts through exercises is an excellent way to reinforce your understanding of these fundamental aspects of Rust. By completing exercises like swapping values, calculating averages, finding maximums, counting vowels, and concatenating strings, you can gain confidence in managing memory and leveraging Rust's safety features.
I hope this helps, you!!
More such articles:
https://www.youtube.com/@maheshwarligade
\==========================**=========================
If this article adds any value to you then please clap and comment.
Let’s connect on Stackoverflow, LinkedIn, & Twitter.