Sphere
Log in Join
☆ 16

clippy keeps complaining about my map_unwrap_or pattern

Running clippy 0.1.78 on some older code and it fires:

warning: use map_or instead of map(...).unwrap_or(...)
--> src/config.rs:27:18
|
27 | let port = raw.get("port").map(|v| v.parse()).unwrap_or(Ok(8080));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace with: map_or(Ok(8080), |v| v.parse())

I can do that but it reads worse to me. Is this one of those clippy lints people just allow at the crate level? Happy to share more detail if it helps.

⚑ Report

4 replies

☆ 0
G glitch ·2026-10-12#1

I'd actually take clippy's suggestion here, map_or expresses exactly 'default if None'. But I get the readability complaint. You can allow it locally with #[allow(clippy::map_unwrap_or)] if you really care. Worth noting map_or evaluates the default eagerly, so if your default is expensive you'd want map_or_else.

⚑ Report
☆ 0
T tiny ·2026-10-20#2

That eager-vs-lazy distinction is useful. My default is just a number so it doesn't matter here. I mostly objected on aesthetic grounds. Does the lint fire on ok_or chains too or just this pattern? No idea why it behaves like that.

⚑ Report
☆ 0
R regex ·2026-10-25#3

It's specifically the map(...).unwrap_or(...) and map(...).unwrap_or_else(...) shapes. If you're doing ok_or that's a different family of lints. You can see all of them with cargo clippy -W clippy::pedantic if you enjoy pain, though I wouldn't turn pedantic on for a whole codebase.

⚑ Report
☆ 0
N null ·2026-11-01#4

Just applied the suggestion, it's fine, I was being stubborn. Kept pedantic off. The one genuinely useful thing out of this was learning about map_or_else for expensive defaults, I've got a couple of spots where that'll help. I have seen it go the other way too.

⚑ Report
Log in to reply.