]>
Commit | Line | Data |
---|---|---|
ba9703b0 | 1 | Only traits defined in the current crate can be implemented for arbitrary types. |
60c5eb7d XL |
2 | |
3 | Erroneous code example: | |
4 | ||
5 | ```compile_fail,E0117 | |
6 | impl Drop for u32 {} | |
7 | ``` | |
8 | ||
9 | This error indicates a violation of one of Rust's orphan rules for trait | |
10 | implementations. The rule prohibits any implementation of a foreign trait (a | |
11 | trait defined in another crate) where | |
12 | ||
13 | - the type that is implementing the trait is foreign | |
14 | - all of the parameters being passed to the trait (if there are any) are also | |
15 | foreign. | |
16 | ||
17 | To avoid this kind of error, ensure that at least one local type is referenced | |
18 | by the `impl`: | |
19 | ||
20 | ``` | |
21 | pub struct Foo; // you define your type in your crate | |
22 | ||
23 | impl Drop for Foo { // and you can implement the trait on it! | |
24 | // code of trait implementation here | |
25 | # fn drop(&mut self) { } | |
26 | } | |
27 | ||
28 | impl From<Foo> for i32 { // or you use a type from your crate as | |
29 | // a type parameter | |
30 | fn from(i: Foo) -> i32 { | |
31 | 0 | |
32 | } | |
33 | } | |
34 | ``` | |
35 | ||
36 | Alternatively, define a trait locally and implement that instead: | |
37 | ||
38 | ``` | |
39 | trait Bar { | |
40 | fn get(&self) -> usize; | |
41 | } | |
42 | ||
43 | impl Bar for u32 { | |
44 | fn get(&self) -> usize { 0 } | |
45 | } | |
46 | ``` | |
47 | ||
48 | For information on the design of the orphan rules, see [RFC 1023]. | |
49 | ||
50 | [RFC 1023]: https://github.com/rust-lang/rfcs/blob/master/text/1023-rebalancing-coherence.md |