Yes, clone()
is the right fix.
If the type is Copy
(all primitive ints are), you don't need to clone()
it, and you would use fn sort<T: Eq + Ord + Copy>
instead. That being said, if you want to remain more generic, then clone()
is fine -- for simple Copy
types like ints, it will be identical to Copy
ing the bits over.
Also, if you use an array (stack-allocated) instead of the Vec
(let mut v = [a, b, c];
), you can avoid a heap allocation.
pub fn sort<T: Eq + Ord + Copy>(tpl: (T, T, T) ) -> (T, T, T){
let (a, b, c) = tpl;
let mut v = [a, b, c];
v.sort();
let [a, b, c] = v;
(v[0], v[1], v[2])
}
Playground
Once the experimental slice pattern syntax on nightly is implemented (IMO) correctly, you could be even more generic by using only moves instead of copies and require no Copy
/Clone
type constraints.
#![feature(slice_patterns)]
pub fn sort<T: Eq + Ord>(tpl: (T, T, T) ) -> (T, T, T){
let (a, b, c) = tpl;
let mut v = [a, b, c];
v.sort();
let [a, b, c] = v;
(a, b, c)
}
But that fails currently because it thinks the let binding is moving out of v
three possibly overlapping times.