Attempted to access a private field on a struct.
Erroneous code example:
#![allow(unused)]
fn main() {
mod some_module {
pub struct Foo {
x: u32,
}
impl Foo {
pub fn new() -> Foo { Foo { x: 0 } }
}
}
let f = some_module::Foo::new();
println!("{}", f.x);
}
ⓘ
If you want to access this field, you have two options:
- Set the field public:
#![allow(unused)]
fn main() {
mod some_module {
pub struct Foo {
pub x: u32,
}
impl Foo {
pub fn new() -> Foo { Foo { x: 0 } }
}
}
let f = some_module::Foo::new();
println!("{}", f.x);
}
- Add a getter function:
#![allow(unused)]
fn main() {
mod some_module {
pub struct Foo {
x: u32,
}
impl Foo {
pub fn new() -> Foo { Foo { x: 0 } }
pub fn get_x(&self) -> &u32 { &self.x }
}
}
let f = some_module::Foo::new();
println!("{}", f.get_x());
}