The example at the end of that section:
pub fn encrypted(&self) -> Vec<u8> {
encrypt(self.payload.as_ref().unwrap_or(&vec![]))
}
Needlessly allocates a `Vec` if `self.payload` is `Some`. Really you should do: encrypt(&self.payload.as_ref().unwrap_or_else(|| &vec![]))
But that isn't going to work because the `else` Vec will be dropped at the end of the closure.In this situation (if the code was on a hot path where every bit of performance mattered) I would probably do something like:
match self.payload.as_ref() {
Some(payload) => encrypt(payload),
None => encrypt(&vec![])
}
There is a slight bit of duplicated code. I'd be curious if anyone could come up with a better way.