]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0616.md
Rollup merge of #92310 - ehuss:rustdoc-ice, r=estebank
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0616.md
1 Attempted to access a private field on a struct.
2
3 Erroneous code example:
4
5 ```compile_fail,E0616
6 mod some_module {
7     pub struct Foo {
8         x: u32, // So `x` is private in here.
9     }
10
11     impl Foo {
12         pub fn new() -> Foo { Foo { x: 0 } }
13     }
14 }
15
16 let f = some_module::Foo::new();
17 println!("{}", f.x); // error: field `x` of struct `some_module::Foo` is private
18 ```
19
20 If you want to access this field, you have two options:
21
22 1) Set the field public:
23
24 ```
25 mod some_module {
26     pub struct Foo {
27         pub x: u32, // `x` is now public.
28     }
29
30     impl Foo {
31         pub fn new() -> Foo { Foo { x: 0 } }
32     }
33 }
34
35 let f = some_module::Foo::new();
36 println!("{}", f.x); // ok!
37 ```
38
39 2) Add a getter function:
40
41 ```
42 mod some_module {
43     pub struct Foo {
44         x: u32, // So `x` is still private in here.
45     }
46
47     impl Foo {
48         pub fn new() -> Foo { Foo { x: 0 } }
49
50         // We create the getter function here:
51         pub fn get_x(&self) -> &u32 { &self.x }
52     }
53 }
54
55 let f = some_module::Foo::new();
56 println!("{}", f.get_x()); // ok!
57 ```