]>
Commit | Line | Data |
---|---|---|
dfeec247 | 1 | A value was moved whose size was not known at compile time. |
60c5eb7d XL |
2 | |
3 | Erroneous code example: | |
4 | ||
5 | ```compile_fail,E0161 | |
94222f64 XL |
6 | trait Bar { |
7 | fn f(self); | |
8 | } | |
9 | ||
10 | impl Bar for i32 { | |
11 | fn f(self) {} | |
12 | } | |
60c5eb7d XL |
13 | |
14 | fn main() { | |
2b03887a | 15 | let b: Box<dyn Bar> = Box::new(0i32); |
94222f64 XL |
16 | b.f(); |
17 | // error: cannot move a value of type dyn Bar: the size of dyn Bar cannot | |
60c5eb7d XL |
18 | // be statically determined |
19 | } | |
20 | ``` | |
21 | ||
22 | In Rust, you can only move a value when its size is known at compile time. | |
23 | ||
24 | To work around this restriction, consider "hiding" the value behind a reference: | |
25 | either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move | |
26 | it around as usual. Example: | |
27 | ||
28 | ``` | |
94222f64 XL |
29 | trait Bar { |
30 | fn f(&self); | |
31 | } | |
32 | ||
33 | impl Bar for i32 { | |
34 | fn f(&self) {} | |
35 | } | |
36 | ||
60c5eb7d | 37 | fn main() { |
2b03887a | 38 | let b: Box<dyn Bar> = Box::new(0i32); |
94222f64 XL |
39 | b.f(); |
40 | // ok! | |
60c5eb7d XL |
41 | } |
42 | ``` |