How do I use Option::unwrap_or_default when it contains a reference?

Viewed 1882

I have a candle_series of the type Vec<Candle> that gets the last element and I try to use unwrap_or_default:

self.candle_series.last().unwrap_or_default()

But then I get this error:

method not found in `std::option::Option<&market::Candle>

How can I get the behaviour of unwrap_or_default on the struct instead of the reference?

My current workaround is this but it seems incorrect. If it is correct, please let me know:

self.candle_series.last().unwrap_or(&Candle::default())
1 Answers

How can I get the behaviour of unwrap_or_default on the struct instead of the reference?

You'd need to either copy or move the reference (e.g. use Option::cloned, assuming your structure is Clone) so that your option is an Option<Candle>, and unwrap_or_default can do its job.

My current workaround is this but it seems incorrect.

Looks fine to me, though of course it might be shorter to use e.g. Candle::new() if you have such an initializer.

Related