Accessing definitions inside functions

I have a module inside a function, which needs to access definitions inside said function (this happens because of proc-macro expansions).

Here is an example:

fn main() {
    const CONSTANT: u8 = 0;
    
    mod private {
        pub fn with_constant() -> u8 {
            super::CONSTANT + 2 // error[E0425]: cannot find value `CONSTANT` in module `super`
        }
    }
    
    println!("{}", private::with_constant());
}

The only way I figured out how to do this is with another module around the mod private:

fn main() {
    use slightly_less_private::*;
    mod slightly_less_private {
        pub const CONSTANT: u8 = 0;
    
        pub mod private {
            pub fn with_constant() -> u8 {
                super::CONSTANT + 2
            }
        }
    }
    
    println!("{}", private::with_constant());
}

But maybe there are better ways?

The only way to do this without breaking rust is by passing that constant as a parameter or by taking that constant outside main or another alternative is to make a "constants module" with all your constants,
What you are asking for is impossible because that private module can be accessed from anywhere in your crate where your 'constant' is not alive

What you are asking for is impossible because that private module can be accessed from anywhere in your crate where your 'constant' is not alive

This is not true, because, first, private module cannot be accessed from anywhere except main function, and, second, CONSTANT is static and alive for the whole duration of the program.

And this is just an example, in my case I need to access struct definitions defined in main, not a constant, so passing it by value wouldn't work.

In Rust a function does not define a namespace that can be used to control visibility and access to declarations, in the ways that a module namespace can. So you need to define another nested module to do that (like you have done), or move the shared declarations up one level to the containing module. That's the way the language is currently defined (for good or bad).

1 Like

I see, thank you!

For me it was unexpected that defining a module and accessing things on its definition level (with super) doesn't work consistently.
Found it out when I was writing tests with definitions inside test functions.

1 Like

I understand. It is natural to think of a function, and in particular a test function, as a namespace like any other namespace. And this difference is not yet very well documented, or at least I can't find any clear documentation about it.