Compile-time checks are not the only place where you can benefit from a performance enhancement at no cost. While in Chapter 1, Common Performance Pitfalls, we saw the common errors people write in Rust, we left the most advanced tips and tricks for this chapter.
Sometimes, it might seem natural to write code that does not perform as fast as expected. Many times, this is due to Rust doing some extra computations at runtime. An example of an unnecessary computation that someone could write is the following:
let opt = Some(123); let non_opt = opt.unwrap_or(some_complex_function());
I have intentionally made this example simply because a real example usually takes really long code. The idea behind it is valid though. When you have an Option
or a Result
, you have some very useful functions to allow you get the value inside or a default. There is this specific function, the unwrap_or()
function, that allows you specify the...