Struct accessibility and submodules


#1

I’ve got the following code:

mod example{
    struct MyStruct{
        member : i32,
    }

    impl MyStruct{
        fn function(&self){
        }
    }

    mod submod {
        use super::*;

        fn broken() {
            let my_struct = MyStruct{member: 2}; //this line blows up: unresolved struct, variant or union type `MyStruct`
            my_struct.function();
        }
    }
}

The documentation states “If an item is private, it may be accessed by the current module and its descendants.” From what I can tell, the submod should be able to see the struct in the parent module above. In addition, marking the struct as ‘pub’ allows the submod to see the private member and function, as I expected. What am I missing here?


#2

I believe this is part of what changed in RFC 1560, particularly this point. It used to be that wildcards (like use super::*;) only imported pub items, but now they’ll pull in all accessible items. The change was stabilized here, which I think has reached beta now.


#3

I don’t follow completely – is this a bug? The following code works, but the second ‘use’ statement is required:

mod example{
    struct MyStruct{
        pub member : i32,
    }

    impl MyStruct{
        fn function(&self){
        }
    }

    mod submod {
        use super::*;
        use super::MyStruct;//this line is required

        fn ok() {
            let my_struct = MyStruct{member: 2}; 
            my_struct.function();
        }
    }
}

#4

It’s less of a bug and more of a historical wart, and the RFC cleans up this behavior. If you’re on the stable compiler (1.14 or earlier) then super::* doesn’t include non-pub items, but in 1.15 it will.


#5

Ah gotcha, makes sense, thanks man