Last active
May 3, 2023 21:01
-
-
Save oshea00/fc9a482ade05b284fa0191139064d3a9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
use std::fmt; | |
use std::cmp::Ordering; | |
#[derive(Debug)] | |
struct Trade { | |
shares: f64, | |
price: f64 | |
} | |
impl Trade { | |
fn amount(&self) -> f64 { | |
self.shares * self.price | |
} | |
} | |
impl fmt::Display for Trade { | |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
write!(f,"Trade{{ shares:{}, price:{}, amount:{} }}", | |
self.shares, self.price, self.amount()) | |
} | |
} | |
impl PartialOrd for Trade { | |
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
self.amount().partial_cmp(&other.amount()) | |
} | |
} | |
impl PartialEq for Trade { | |
fn eq(&self, other: &Self) -> bool { | |
self.amount() == other.amount() | |
} | |
} | |
fn largest<T: PartialOrd>(list: &[T]) -> &T { | |
let mut largest = &list[0]; | |
for item in list { | |
if item > largest { | |
largest = item; | |
} | |
} | |
largest | |
} | |
fn main() { | |
let number_list = vec![34, 50, 25, 100, 65]; | |
let result = largest::<i32>(&number_list); | |
println!("The largest number is {}", result); | |
let char_list = vec!['y', 'm', 'a', 'q']; | |
let result = largest::<char>(&char_list); | |
println!("The largest char is '{}'", result); | |
let trades = vec![ | |
Trade { | |
shares: 10.0, | |
price: 15.50 | |
}, | |
Trade { | |
shares: 5.0, | |
price: 100.10 | |
}]; | |
let result = largest::<Trade>(&trades); | |
println!("The largest Trade is {}", result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment