Skip to content

Documentation: accessing the private items of a parent module #31309

@swatteau

Description

@swatteau

When accessing items defined in the parent module, it is tempting to write use super::*;. However, this does not allow accessing private items. For example, this fails:

fn print_hello() {
    println!("hello");
}

mod inner {
    use super::*;
    pub fn do_something() {
        print_hello(); // error: unresolved name `print_hello` [E0425]
    }
}

This is a mistake I've made several times (I suspect many others have too) and the solution is to be explicit about the item used, either with

use super::print_hello;

or

super::print_hello();

On this topic, the Rust Reference says:

Use declarations support a number of convenient shortcuts:

  • ...
  • Binding all paths matching a given prefix, using the asterisk wildcard syntax use a::b::*;
  • ...

I find this a bit misleading because the asterisk wildcard syntax really only binds public paths matching a given prefix.

I think it would be nice to add a paragraph in the Rust Book to explain how to access private items properly and to state clearly that use super::* won't help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions