blob: 5acbc6e44e12c094a9808b1c1578ae630f9dec0d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
Attempted to access a private field on a struct.
Erroneous code example:
```compile_fail,E0616
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
```
If you want to access this field, you have two options:
1) Set the field public:
```
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!
```
2) Add a getter function:
```
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!
```
|