What is the realistic meaning of the pub(self)

Functions declared using pub(self) syntax are only visible within the current module, which is the same as leaving them private.

What is the practical significance of it ?

What is the difference of it and default private?

As far as I can tell, it doesn't do anything. I think it exists just for consistency (e.g. to make it easier to generate syntax in macros).

1 Like

Great man think alike :sunglasses:

Sometimes getting privacy right can be paramount, especially when dealing with unsafe code or other safety-related abstractions. In that case, if there is a function that is usually public such as a constructor that has to be private, I personally like to add a pub(self) // private! annotation on it just to make it the intent super explicit and be more robust to future changes.

3 Likes

Someone correct me if I'm wrong, but my understanding is that private fields are visible within the module declaring the type as well as any sub-modules; however, pub(self) types are only visible within the direct module that contains the type. Nope, this is incorrect. I just verified in "The Book" (https://doc.rust-lang.org/reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself). pub(self) and private are exactly the same thing.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.