Add global imports to rust

if am using a project with a lot of files with a lot of crates i am going to import the dependencies manually so my idea is to use a global keyword

example:

global use dotenvy::dotenv;

this makes all rust files on this directory or subdirectories automatically include dotenvy without needing to use the dotenvy crate a lot of times

If I understand correctly this will make function dotenvy::dotenv available as dotenv to all files recursively within this directory, right?

If that's the case, my main concern is same-name conflicts. Say you have a library that does IO, so you write global use std::io::Result, but you also want some types to implement Display, so you write use std::fmt::Result. Without some kind of resolution, it can be counterintuitive. (playground) Though, come to think of it, I don't know how the std prelude deals with it (this compiles fine instead of conflicting with the default std::result::Result).

The second concern is it can pollute the namespace of code in include_file!.

As for current alternatives, I think it's sufficient to create a common_use.rs as a prelude module:

pub use dotenvy::dotenv;

and code will write use common_use::*; and it has the advantage that it's explicit, doesn't have to be in file scope, and provides easier opt-out.

6 Likes

One of the main benefits provided by Rust language design is to enable local understanding of any given source code by enforcing an explicit style (e.g. function signatures without non-local inference). The same applies to names used within a module. Therefore, I posit that the proposed feature runs counter to existing language design principles.

The feature of wildcard imports has already been noted as a way to consolidate imports if you don't want your code to be readable (meaning: get fully qualified names) outside an IDE.

7 Likes