Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub fn largest<T: PartialOrd>(list: &[T]) -> &T {
- // Start by grabbing an immutable reference to the first element in the slice
- // While we won't mutate the underlying T element, we WILL mutate the pointer
- // Therefore the reference (largest) was declared as mutable
- let mut largest: &T = &list[0];
- // For each item in the slice, get an immutable reference to it
- for item in list.iter() {
- // If the item is larger (according to PartialOrd trait) than the value pointed at by "largest"
- if item > largest {
- // Change the "largest" pointer to instead point to this item
- largest = &item;
- }
- }
- // Return "largest"
- largest
- }
- fn main() {
- let v = vec![1u32, 2u32];
- println!("{}",largest(&v));
- println!("{:?}",v);
- }
Add Comment
Please, Sign In to add comment