ralfbiedert / cheats.rs

Rust Language Cheat Sheet - https://cheats.rs
https://cheats.rs
4.14k stars 395 forks source link

`fn f() where Self: R {} Other R useful w. dflt. fn. (non dflt. would need be impl'ed anyway).` #187

Closed xxshady closed 1 year ago

xxshady commented 1 year ago

изображение

What does it mean?

ralfbiedert commented 1 year ago

Apologies, I'm not really happy about that line as it's too condensed. The literal expansion is

Other R bounds can be useful with default functions (fn). (Non default ones would need be implemented anyway).

What it means is, the act of applying an where Self: R bound to a function can be useful in cases where you want that function to be only available if the type in question also implements an optional R.

The R is optional in this case because if you wanted it mandatory you'd already have made it mandatory in your trait declaration like so trait T: R.

The part about "Non default ones would need be implemented anyway" means that adding a where Self: R is useless in non-default functions: If you had a fn f() where Self: R; and left it to the implementing third party, ~that party would have a problem. It must implement f as it's a trait requirement, but it could only do so if the type in question "accidentally" also implemented R (as it was not mandatory to start with)~

Update, just remembered the where Self: R is about visibility for the caller, you can implement f in any case.

xxshady commented 1 year ago

Thanks for the explanation