Guest User

Untitled

a guest
Oct 18th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. pub fn largest<T: PartialOrd>(list: &[T]) -> &T {
  2.  
  3. // Start by grabbing an immutable reference to the first element in the slice
  4. // While we won't mutate the underlying T element, we WILL mutate the pointer
  5. // Therefore the reference (largest) was declared as mutable
  6. let mut largest: &T = &list[0];
  7.  
  8. // For each item in the slice, get an immutable reference to it
  9. for item in list.iter() {
  10.  
  11. // If the item is larger (according to PartialOrd trait) than the value pointed at by "largest"
  12. if item > largest {
  13.  
  14. // Change the "largest" pointer to instead point to this item
  15. largest = &item;
  16.  
  17. }
  18. }
  19.  
  20. // Return "largest"
  21. largest
  22. }
  23.  
  24. fn main() {
  25. let v = vec![1u32, 2u32];
  26. println!("{}",largest(&v));
  27. println!("{:?}",v);
  28.  
  29. }
Add Comment
Please, Sign In to add comment