Diti

Cow – Clone on write

Apr 12th, 2019
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.71 KB | None | 0 0
  1. // https://doc.rust-lang.org/std/borrow/enum.Cow.html
  2.  
  3. use std::borrow::Cow;
  4.  
  5. fn abs_all(input: &mut Cow<[i32]>) {
  6.     for i in 0..input.len() {
  7.         let v = input[i];
  8.         if v < 0 {
  9.             // Clones into a vector if not already owned.
  10.             input.to_mut()[i] = -v;
  11.         }
  12.     }
  13. }
  14.  
  15. // No clone occurs because `input` doesn't need to be mutated.
  16. let slice = [0, 1, 2];
  17. let mut input = Cow::from(&slice[..]);
  18. abs_all(&mut input);
  19.  
  20. // Clone occurs because `input` needs to be mutated.
  21. let slice = [-1, 0, 1];
  22. let mut input = Cow::from(&slice[..]);
  23. abs_all(&mut input);
  24.  
  25. // No clone occurs because `input` is already owned.
  26. let mut input = Cow::from(vec![-1, 0, 1]);
  27. abs_all(&mut input);
Advertisement
Add Comment
Please, Sign In to add comment