Skip to content

Commit a5d33d8

Browse files
committed
Auto merge of #27182 - AlisdairO:diagnostics382, r=Manishearth
As title :-) Part of #24407. r? @Manishearth
2 parents cbf4c34 + dadc717 commit a5d33d8

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

src/librustc_borrowck/diagnostics.rs

+63-1
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,69 @@ To fix this, ensure that any declared variables are initialized before being
7575
used.
7676
"##,
7777

78+
E0382: r##"
79+
This error occurs when an attempt is made to use a variable after its contents
80+
have been moved elsewhere. For example:
81+
82+
```
83+
struct MyStruct { s: u32 }
84+
85+
fn main() {
86+
let mut x = MyStruct{ s: 5u32 };
87+
let y = x;
88+
x.s = 6;
89+
println!("{}", x.s);
90+
}
91+
```
92+
93+
Since `MyStruct` is a type that is not marked `Copy`, the data gets moved out
94+
of `x` when we set `y`. This is fundamental to Rust's ownership system: outside
95+
of workarounds like `Rc`, a value cannot be owned by more than one variable.
96+
97+
If we own the type, the easiest way to address this problem is to implement
98+
`Copy` and `Clone` on it, as shown below. This allows `y` to copy the
99+
information in `x`, while leaving the original version owned by `x`. Subsequent
100+
changes to `x` will not be reflected when accessing `y`.
101+
102+
```
103+
#[derive(Copy, Clone)]
104+
struct MyStruct { s: u32 }
105+
106+
fn main() {
107+
let mut x = MyStruct{ s: 5u32 };
108+
let y = x;
109+
x.s = 6;
110+
println!("{}", x.s);
111+
}
112+
```
113+
114+
Alternatively, if we don't control the struct's definition, or mutable shared
115+
ownership is truly required, we can use `Rc` and `RefCell`:
116+
117+
```
118+
use std::cell::RefCell;
119+
use std::rc::Rc;
120+
121+
struct MyStruct { s: u32 }
122+
123+
fn main() {
124+
let mut x = Rc::new(RefCell::new(MyStruct{ s: 5u32 }));
125+
let y = x.clone();
126+
x.borrow_mut().s = 6;
127+
println!("{}", x.borrow.s);
128+
}
129+
```
130+
131+
With this approach, x and y share ownership of the data via the `Rc` (reference
132+
count type). `RefCell` essentially performs runtime borrow checking: ensuring
133+
that at most one writer or multiple readers can access the data at any one time.
134+
135+
If you wish to learn more about ownership in Rust, start with the chapter in the
136+
Book:
137+
138+
https://doc.rust-lang.org/book/ownership.html
139+
"##,
140+
78141
E0384: r##"
79142
This error occurs when an attempt is made to reassign an immutable variable.
80143
For example:
@@ -100,7 +163,6 @@ fn main(){
100163
}
101164

102165
register_diagnostics! {
103-
E0382, // use of partially/collaterally moved value
104166
E0383, // partial reinitialization of uninitialized structure
105167
E0385, // {} in an aliasable location
106168
E0386, // {} in an immutable container

0 commit comments

Comments
 (0)