Skip to content

Ability to refer to a path relative to the current scope in use declarations #959

@crumblingstatue

Description

@crumblingstatue

(Note that this is not about the ability to refer to the current module, which is already possible with use self::foo.)

Rust allows declaring modules, enums, and extern crates in most places where items can be declared, including block scopes inside functions.
One use of this is bringing an extern crate into scope inside a conditional branch:

fn show_message(message: &str) {
    if (inside_a_gui_context) {
        extern crate messagebox;
        // Import trait Messagebox
        use messagebox::Messagebox; // Doesn't work
        ...
    } else {
        println!("{}", message);
    }
}

The problem is that there is no way to refer to items declared this way in use declarations, as paths in use declarations are absolute.

It feels inconsistent being able to declare items like this, but not being able to refer to them in use declarations, and might surprise some users. It did surprise me.

While referring to the items inside can be done by using their full relative path (e.g. do_something_with(messagebox::foo)), there is no way to import traits, so the user has to move the module/crate up to a scope where it can be referred from in use declarations.

One way this could be resolved is to give users a way to refer to a relative path in use declarations.

Options include:

  • Using a keyword , e.g. use relative::messagebox::Messagebox, although I'm not sure reserving a new keyword this late in the alpha is desirable.
  • Using _, as in use _::messagebox::Messagebox, but I'm not sure if _ could otherwise refer to a valid path. It's also not as descriptive as a keyword, but still better than nothing.

The general ability to use relative paths in use declarations might also bring ergonomic benefits in other cases too.

Any thoughts on this issue?

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions