eyre-rs / color-eyre

Custom hooks for colorful human oriented error reports via panics and the eyre crate
Other
958 stars 57 forks source link

Can you explain the .map(drop) in usage example? #116

Closed fleetingbytes closed 2 years ago

fleetingbytes commented 2 years ago

Hi, I'm quite new to rust and I'm just starting to use this library for better error output. I don't understand how can the usage.rs example even run. There is this line with .map(drop) which is completely obscure to me. As far as I have learned, map expects a Closure, but drop does not look like a closure, nor has it been defined as a variable. What does it do?

If drop is a function which is in scope by default, it could be https://doc.rust-lang.org/stable/std/ops/trait.Drop.html, which one tries to execute on a String. But since String is Clone (not Drop), it produces some sort of an error, is that it?

yaahc commented 2 years ago

Happy to explain!

The drop there is referring to std::mem::drop^1, which is a free function in the prelude^2 not a closure.

The reason this works with map is because map expects any arbitrary type that implements the FnOnce(T) -> U trait, which is implemented automatically for both closures and for functions or even for any arbitrary type on nightly if you enable the fn_traits feature and implement FnOnce manually. The end result is that drop ends up being called on the String from the previous function in the Ok case which just throws it away and replaces it with the unit type () aka nothing.

fleetingbytes commented 2 years ago

Thank you very much for the thorough explanation. It helped me to learn a great deal of rust basics as I followed the paths in this rabbit hole.