Armed with the knowledge I had gained from answers (Thanks again!) to this question on Stackoverflow, I had written this:
pub struct AggregateDataPerConnection {
pub connection_idx: u16,
pub ok_duration_series: Vec<u128>,
pub mx_time_spent_on_ok_req: u128,
}
// TODO: Provide a Builder for the struct below!
impl AggregateDataPerConnection {
pub fn new(
connection_idx: u16, ok_duration_series: Vec<u128>
) -> AggregateDataPerConnection {
AggregateDataPerConnection {
connection_idx,
ok_duration_series,
mx_time_spent_on_ok_req: ok_duration_series.iter().copied().max().unwrap_or(0)
}
}
}
The compiler was not happy:
Compiling playground v0.0.1 (/playground)
error[E0382]: borrow of moved value: `ok_duration_series`
--> src/lib.rs:20:38
|
12 | connection_idx: u16, ok_duration_series: Vec<u128>
| ------------------ move occurs because `ok_duration_series` has type `Vec<u128>`, which does not implement the `Copy` trait
...
19 | ok_duration_series,
| ------------------ value moved here
20 | mx_time_spent_on_ok_req: ok_duration_series.iter().copied().max().unwrap_or(0)
| ^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
|
= note: borrow occurs due to deref coercion to `[u128]`
For more information about this error, try `rustc --explain E0382`.
I had reasoned - aided by the compiler - because the move happened before the max was calculated, I could postpone the move, by lexical scoping, like this:
impl AggregateDataPerConnection {
pub fn new(
connection_idx: u16, ok_duration_series: Vec<u128>
) -> AggregateDataPerConnection {
AggregateDataPerConnection {
connection_idx,
mx_time_spent_on_ok_req: ok_duration_series.iter().copied().max().unwrap_or(0),
ok_duration_series
}
}
}
This worked to my relief! :-)
However, I am not confident if my reasoning is correct.
As I am reflecting upon this:
Because the compiler has the complete view of what I intend to do, inside a constructor of the struct, it already knows that there is no way that the control (at the runtime) can seep through (making the Vec
vulnerable), during the construction and therefore, the compiler can detect the max w/o having to move the vector. In any case, the movement of the ownership is towards a member of the same struct being constructed.
Please make me wiser.