29 ms·
> "Pure functions" is usually a bad idea with large numeric data structures if they are non-lazy - because you'll end up copying the data. This isn't necessari
by nightcracker 7y ago
> "Pure functions" is usually a bad idea with large numeric data structures if they are non-lazy - because you'll end up copying the data.
This isn't necessarily true due to Rust's strong ownership. Methods can take `self` (without reference) as an argument which means the method takes ownership of itself. There is no copy for 'double' in the below example, yet it is pure:
#[derive(Clone)]
struct A {
v: Vec<i32>,
}
impl A {
fn double(mut self) -> Self {
for x in &mut self.v {
*x *= 2;
}
self
}
}
fn main() {
let a = A { v: vec![2, 3, 4] };
let b = a.double();
dbg!(b.v[1]);
}
If you now tried to access `a` the compiler would error out, saying you're trying to access a moved-from variable. If you still wanted to keep the original `a` around you simply write `let b = a.clone().double()`.