Created
March 1, 2025 11:02
-
-
Save vijayanant/8b396e1415a72eeb0b27abd28b6ee13c to your computer and use it in GitHub Desktop.
Rust - Traits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Summable { | |
fn zero() -> Self; | |
fn add(&self, other: &Self) -> Self; | |
} | |
impl Summable for i32 { | |
fn zero() -> Self { | |
0 | |
} | |
fn add(&self, other: &Self) -> Self { | |
self + other | |
} | |
} | |
impl Summable for f64 { | |
fn zero() -> Self { | |
0.0 | |
} | |
fn add(&self, other: &Self) -> Self { | |
self + other | |
} | |
} | |
impl Summable for String { | |
fn zero() -> Self { | |
String::new() | |
} | |
fn add(&self, other: &Self) -> Self { | |
let mut result = self.clone(); | |
result.push_str(other); | |
result | |
} | |
} | |
impl<T: Summable + Clone> Summable for Option<T> { | |
fn zero() -> Self { | |
None | |
} | |
fn add(&self, other: &Self) -> Self { | |
match (self, other) { | |
(Some(x), Some(y)) => Some(x.add(y)), | |
(Some(_), None) => self.clone(), | |
(None, Some(_)) => other.clone(), | |
(None, None) => None, | |
} | |
} | |
} | |
fn sum<T: Summable>(values: &[T]) -> T | |
where | |
T: Clone, | |
{ | |
let mut result = T::zero(); | |
for value in values { | |
result = result.add(value); | |
} | |
result | |
} | |
#[test] | |
fn test_i32_sum() { | |
let numbers: Vec<i32> = vec![1, 2, 3]; | |
assert_eq!(sum(&numbers), 6); | |
} | |
#[test] | |
fn test_f64_sum() { | |
let floats: Vec<f64> = vec![1.1, 2.2, 3.3]; | |
assert_eq!(sum(&floats), 6.6); | |
} | |
#[test] | |
fn test_option_f64_sum() { | |
let option_floats: Vec<Option<f64>> = vec![Some(1.1), None, Some(2.5)]; | |
assert_eq!(sum(&option_floats), Some(3.6)); | |
} | |
#[test] | |
fn test_option_i32_sum_negative(){ | |
let option_numbers: Vec<Option<i32>> = vec![Some(-1), Some(2), Some(-3)]; | |
assert_eq!(sum(&option_numbers), Some(-2)); | |
} | |
#[test] | |
fn test_string_sum() { | |
let strings: Vec<String> = vec!["Hello".to_string(), " ".to_string(), "World".to_string()]; | |
assert_eq!(sum(&strings), "Hello World".to_string()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment