Are some items just inaccessible from nested modules?

Is there a way to access a static item from within a nested module as follows?

static GALLIUM_GIRL:i64 = 1000;
fn b() {
    static BORON_BOY:i32 = -300; 
    
    mod c {
        use super::*;
        static G: i64 = GALLIUM_GIRL;
        static B: i32 = BORON_BOY; // errors        
    }
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0425]: cannot find value `BORON_BOY` in this scope
 --> src/lib.rs:8:25
  |
8 |         static B: i32 = BORON_BOY;
  |                         ^^^^^^^^^ not found in this scope

For more information about this error, try `rustc --explain E0425`.
error: could not compile `playground` (lib) due to 1 previous error

Looking at the rust doc, super doesn't work because, super is defined as resolving "to the parent of the current module" (Paths - The Rust Reference).

Why does it matter? Sometimes when generating tests for crate with different features, it's helpful to create nested modules in the test function to share common settings but avoid naming collisions for generated code.

super goes up one module, super::super goes up two modules, and so on. crate refers to your root module.

In filesystem terms/analogy, .. is super, crate is /.

Edit: I didn't see that b is a function. That static item is completely private to that function and cannot be observed. A module defined inside that function doesn't get access to items defined in it.

4 Likes

Thanks. I wonder if there's a reason for this other than it being a side effect of how visibility/observability works.

A module defined inside a function doesn't work like you think it does. A module defined inside a function is the same as a same named module outside that function.

2 Likes

(Sniped :sweat_smile:)

In general, items (mod, another fn, ...) in function bodies act like items defined at the module level. For example this doesn't work either.

fn example<T>() {
    fn attempt_to_take_outer_generic(_: T) {}
}

(Which may or may not be included in what you meant by visibility/observability.)

3 Likes

Thank you, I had always wondered why I couldn't do that. :grinning:

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.