lotsoftools

Understanding Rust Error E0616: Accessing Private Fields

Introduction to Rust Error E0616

Rust Error E0616 occurs when attempting to access a private field within a struct. In Rust, fields are private by default, and can only be accessed within the module they're defined in. This error can be resolved by making the field public or adding a getter function.

Erroneous Code Example

#![allow(unused)]
fn main() {
mod some_module {
    pub struct Foo {
        x: u32, // So `x` is private in here.
    }

    impl Foo {
        pub fn new() -> Foo { Foo { x: 0 } }
    }
}

let f = some_module::Foo::new();
println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
}

Solution 1: Set the field public

Making the field public allows it to be accessible from outside the module. To do this, add the 'pub' keyword before the field type.

#![allow(unused)]
fn main() {
mod some_module {
    pub struct Foo {
        pub x: u32, // `x` is now public.
    }

    impl Foo {
        pub fn new() -> Foo { Foo { x: 0 } }
    }
}

let f = some_module::Foo::new();
println!("{}", f.x); // ok!
}

Solution 2: Add a getter function

Adding a getter function allows controlled access to the private field, without making it public. The getter function should be defined within the 'impl' block.

#![allow(unused)]
fn main() {
mod some_module {
    pub struct Foo {
        x: u32, // So `x` is still private in here.
    }

    impl Foo {
        pub fn new() -> Foo { Foo { x: 0 } }

        // We create the getter function here:
        pub fn get_x(&self) -> &u32 { &self.x }
    }
}

let f = some_module::Foo::new();
println!("{}", f.get_x()); // ok!
}