Define default value for struct imported from module


#1

If I define a struct in a module like:

foo.rs:

pub struct Bar {
    bar: bool
}

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

baz.rs:

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.


#2

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.


#3

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


#4

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


#5

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: http://play.rust-lang.org/?gist=45aa25b52e0e643557ace3d3087cad04&version=stable&mode=debug&edition=2015
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.


#6

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.