Anonymous impl oddities?


Hello everyone,

right now I am writing my first crate and was thinking about ways to structure things. In this process I dug out an old RFC that was implemented (I think):

First thing: the bad example in the text works.
Secondly: also a modification works that I find a bit ugly:

Why is line 17 ok? Shouldn’t it be break2::MyGuy::do2()?


It’s OK to define an inherent impl anywhere. You can make individual methods private to hide them from other modules.

Here is the RFC that reverted 0155:


Ah OK, i did not see the second RFC. But regarding my example, why do i have to refer to the first module for do2()?


I think you always have to point at the module where the original struct was defined.


You always refer to the type itself (think the struct MyGuy), which is in break1.

It’s the same as when implementing traits: you can implement them anywhere (as long as either the trait or the type is in the current crate), but you still refer to the trait methods by the type, wherever it is defined.

By the way, since that RFC the terminology changed a bit: the “anonymous trait impls” are now called “inherent impls”.


OK. So by ‘attaching’ a function from a different module do2() is automatically in scope when i refer to the module break1?


Yes; that is similar to trait impls that are in scope whenever the trait itself is in scope.

It’s still not something you’ll find a lot in Rust crates; I imagine that it would only come in handy for very large types, for example, where you want to split the impl across different files.

Another thing I just realized is that privacy rules still apply for members: if your method is in a different module, it can’t access non-pub members of the struct. It may be surprising, but is logical because in Rust privacy is defined in terms of modules, not types.

By the way, there’s a proposal to extend this to other crates on the internals forum:


I think I get it now :slight_smile: it makes sense but it is not very intuitive at first. Thank you!