Using a function returning a struct from another crate

I noticed in my project that if I use a function defined in a different crate, which returns a struct, I don't need to make the struct visible. As long as I make the function visible the compiler is happy. Is this correct as per the language? Shouldn't I have to make the struct visible as well?

Here is an example:

// crate c1, module m1

pub struct SomeStruct {
  pub name : String
}

pub fn something () -> SomeStruct {
}

// crate c2

use c1::m1::something;

fn main () {
  // I can call something () and even see the 'name' field of the struct
  // even though I haven't made SomeStruct visible
}

Yes, this works as intended.

Note that if by "make visible" you mean the use statement, then it's not necessary at all in this case. This will work too:

fn main() {
    // both the struct and the function are visible already
    let _: c1::m1::SomeStruct = c1::m1::something();
}
1 Like

The use here isn't really making anything "visible," it's bringing the name of the function/trait/type/etc into scope. So if you had to actually type the name of the struct in to your program, you'd have to either bring the name into scope via use, or do what @Cerber-Ursi has and use fully-qualified names.

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.