Rust

Rust

By DeepSource

Usage of expect followed by a function call RS-W1030

Performance

Calls to expect followed by a function call should be replaced with unwrap_or_else to increase laziness. The argument to expect is evaluated eagerly and unconditionally. The argument to unwrap_or_else is evaluated lazily and only if required, sometimes leading to lower overhead and fewer allocations.

Replace the call to expect with unwrap_or_else. Modify the argument accordingly.

Examples

Bad practice

// allocates a string even if `foo` is `Ok(_)`
foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());

Recommended

// only allocates if `foo` evaluates to `Err(_)`
foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));