#mutable references as arguments for generic functions

2 messages · Page 1 of 1 (latest)

orchid jewel
#

I am attempting to practice using the strategy pattern and thought to sort a vector using a function selected at runtime, ideally being able to change the data in place using a mutable reference.

I tried to add the keyword &mut in multiple places but could not figure out how to get my code to work with the mutable references.

Here is my code as a rust playground link https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bffd720880c4a316dfeca0ee57d27a44

Any advice on how to do this, or improvements on my code would be greatly appreciated. Thanks

rich thunder
# orchid jewel I am attempting to practice using the strategy pattern and thought to sort a vec...

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=47133e56b74e71ddb4cd112add7f5e0a

-pub fn sort(mut self) -> Self {
-    self.sort_data = (self.sort_strategy)(self.sort_data);
-    self
-}
+pub fn sort(&mut self) {
+    self.sort_data = (self.sort_strategy)(std::mem::take(&mut self.sort_data));
+}

You need to use std::mem::take for the vec, because sort_strategy takes a Vec by value, and you cannot move out of a field of a borrowed value.
Vec::default is cheap, so it's fine to use std::mem::take here.