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