8.17 Exercises
Click to see the list of suggested exercises
-
Maximum Function Variants
-
Variant 1: Write a function
max_i32
that takes twoi32
parameters and returns the maximum value.fn max_i32(a: i32, b: i32) -> i32 { if a > b { a } else { b } } fn main() { let result = max_i32(3, 7); println!("The maximum is {}", result); }
-
Variant 2: Write a function
max_ref
that takes references toi32
values and returns a reference to the maximum value.fn max_ref<'a>(a: &'a i32, b: &'a i32) -> &'a i32 { if a > b { a } else { b } } fn main() { let x = 5; let y = 10; let result = max_ref(&x, &y); println!("The maximum is {}", result); }
-
Variant 3: Write a generic function
max_generic
that works with any type that implements thePartialOrd
andCopy
traits.fn max_generic<T: PartialOrd + Copy>(a: T, b: T) -> T { if a > b { a } else { b } } fn main() { let int_max = max_generic(3, 7); let float_max = max_generic(2.5, 1.8); println!("The maximum integer is {}", int_max); println!("The maximum float is {}", float_max); }
-
-
String Concatenation: Write a function
concat
that takes two string slices and returns a newString
containing both.fn concat(s1: &str, s2: &str) -> String { let mut result = String::from(s1); result.push_str(s2); result } fn main() { let result = concat("Hello, ", "world!"); println!("{}", result); }
-
Distance Calculation: Define a function that calculates the Euclidean distance between two points in 2D space, using tuples as parameters.
fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 { let dx = p2.0 - p1.0; let dy = p2.1 - p1.1; (dx * dx + dy * dy).sqrt() } fn main() { let point1 = (0.0, 0.0); let point2 = (3.0, 4.0); println!("Distance: {}", distance(point1, point2)); }
-
Array Reversal: Write a function that takes a mutable slice of
i32
and reverses its elements in place.fn reverse(slice: &mut [i32]) { let len = slice.len(); for i in 0..len / 2 { slice.swap(i, len - 1 - i); } } fn main() { let mut data = [1, 2, 3, 4, 5]; reverse(&mut data); println!("Reversed: {:?}", data); }
-
Implementing
find
Function: Write a function that searches for an element in a slice and returns its index usingOption<usize>
.fn find(slice: &[i32], target: i32) -> Option<usize> { for (index, &value) in slice.iter().enumerate() { if value == target { return Some(index); } } None } fn main() { let numbers = [10, 20, 30, 40, 50]; match find(&numbers, 30) { Some(index) => println!("Found at index {}", index), None => println!("Not found"), } }