Search code examples
structmodulerustpublic

Avoiding pubs in Rust


I've just split my program into an executable and a large file full of struct definitions (structs.rs).

In order to use the structs and their fields for the main executable, I have to prepend each struct definition, and every field definition with pub.

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Foo {
    pub bar: u8,
    pub baz: [u8; 4]
}

This reduces readability.

Is there a way of avoiding all of these pubs?

Or should I be using another way of decomposing my program into multiple files?


Solution

  • This is expected. Modules and crates are a privacy boundary in Rust. The default privacy level for structs and their fields is "same module and its submodules", so parent modules and sibling modules need to have a permission to touch struct's fields.

    In Rust structs typically have only a few fields, but the fields may have important invariants to uphold. For example, if Vec.len was public, you could cause unsafe out of bounds access. As a precaution, Rust requires programmers to think through whether they can allow access to each field.

    It's unusual to have thousands of structs or structs with thousands of fields, unless they're mirroring some external data definition. If that's the case, consider auto-generating struct definitions with a macro or build.rs.