Define default value for struct imported from module

If I define a struct in a module like:

pub struct Bar {
    bar: bool

can I import that into another module and define a default like:

use foo::Bar;

impl Default for foo::Bar {
    Bar {
        bar: true

Can’t seem to get it to work and not sure if it’s just impossible or I’m not doing it correctly.

You need to make struct Bar be pub or pub(crate) (same for its members) if you want module baz to be able to access it.

Sorry that was a mistake in the original post but my code is already ‘pub’.

yes, but, the field is private. Make the field pub(crate) to allow other modules in the crate to access it.

1 Like

I hope you got your code to work.
Apart from the visibility, the code as you posted it still has a few errors / typos. Here’s a version that compiles, I hope it’s what you had in mind:
I am also curious why you’d want to implement the Default trait for Bar in anouther module. If it’s for organizing your codebase, fine. But keep in mind this code does exactly the same as if the impl Default for Bar was written inside the module foo.
In particular, you can’t write another impl Default for Bar in a different module, if that’s what you had in mind.

yes this is the crux of the problem. I suppose I'll have to wrap the struct in another to define the defaults per module. Thanks for your insight.