]> git.lizzy.rs Git - rust.git/blob - src/librustc_error_codes/error_codes/E0277.md
Auto merge of #66396 - smmalis37:pythontest, r=alexcrichton
[rust.git] / src / librustc_error_codes / error_codes / E0277.md
1 You tried to use a type which doesn't implement some trait in a place which
2 expected that trait. Erroneous code example:
3
4 ```compile_fail,E0277
5 // here we declare the Foo trait with a bar method
6 trait Foo {
7     fn bar(&self);
8 }
9
10 // we now declare a function which takes an object implementing the Foo trait
11 fn some_func<T: Foo>(foo: T) {
12     foo.bar();
13 }
14
15 fn main() {
16     // we now call the method with the i32 type, which doesn't implement
17     // the Foo trait
18     some_func(5i32); // error: the trait bound `i32 : Foo` is not satisfied
19 }
20 ```
21
22 In order to fix this error, verify that the type you're using does implement
23 the trait. Example:
24
25 ```
26 trait Foo {
27     fn bar(&self);
28 }
29
30 fn some_func<T: Foo>(foo: T) {
31     foo.bar(); // we can now use this method since i32 implements the
32                // Foo trait
33 }
34
35 // we implement the trait on the i32 type
36 impl Foo for i32 {
37     fn bar(&self) {}
38 }
39
40 fn main() {
41     some_func(5i32); // ok!
42 }
43 ```
44
45 Or in a generic context, an erroneous code example would look like:
46
47 ```compile_fail,E0277
48 fn some_func<T>(foo: T) {
49     println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
50                            //        implemented for the type `T`
51 }
52
53 fn main() {
54     // We now call the method with the i32 type,
55     // which *does* implement the Debug trait.
56     some_func(5i32);
57 }
58 ```
59
60 Note that the error here is in the definition of the generic function: Although
61 we only call it with a parameter that does implement `Debug`, the compiler
62 still rejects the function: It must work with all possible input types. In
63 order to make this example compile, we need to restrict the generic type we're
64 accepting:
65
66 ```
67 use std::fmt;
68
69 // Restrict the input type to types that implement Debug.
70 fn some_func<T: fmt::Debug>(foo: T) {
71     println!("{:?}", foo);
72 }
73
74 fn main() {
75     // Calling the method is still fine, as i32 implements Debug.
76     some_func(5i32);
77
78     // This would fail to compile now:
79     // struct WithoutDebug;
80     // some_func(WithoutDebug);
81 }
82 ```
83
84 Rust only looks at the signature of the called function, as such it must
85 already specify all requirements that will be used for every type parameter.