Anonymous impl oddities?


#1

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:
https://is.gd/mwFL0c

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


#2

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: https://github.com/rust-lang/rfcs/blob/master/text/0735-allow-inherent-impls-anywhere.md


#3

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()?


#4

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


#5

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”.


#6

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


#7

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: https://internals.rust-lang.org/t/pre-rfc-inherent-methods-from-any-crate/3821


#9

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