compiler/rustc_error_codes/src/error_codes/E0277.md MARKDOWN 88 lines View on github.com → Search inside
1You tried to use a type which doesn't implement some trait in a place which2expected that trait.34Erroneous code example:56```compile_fail,E02777// here we declare the Foo trait with a bar method8trait Foo {9    fn bar(&self);10}1112// we now declare a function which takes an object implementing the Foo trait13fn some_func<T: Foo>(foo: T) {14    foo.bar();15}1617fn main() {18    // we now call the method with the i32 type, which doesn't implement19    // the Foo trait20    some_func(5i32); // error: the trait bound `i32 : Foo` is not satisfied21}22```2324In order to fix this error, verify that the type you're using does implement25the trait. Example:2627```28trait Foo {29    fn bar(&self);30}3132// we implement the trait on the i32 type33impl Foo for i32 {34    fn bar(&self) {}35}3637fn some_func<T: Foo>(foo: T) {38    foo.bar(); // we can now use this method since i32 implements the39               // Foo trait40}4142fn main() {43    some_func(5i32); // ok!44}45```4647Or in a generic context, an erroneous code example would look like:4849```compile_fail,E027750fn some_func<T>(foo: T) {51    println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not52                           //        implemented for the type `T`53}5455fn main() {56    // We now call the method with the i32 type,57    // which *does* implement the Debug trait.58    some_func(5i32);59}60```6162Note that the error here is in the definition of the generic function. Although63we only call it with a parameter that does implement `Debug`, the compiler64still rejects the function. It must work with all possible input types. In65order to make this example compile, we need to restrict the generic type we're66accepting:6768```69use std::fmt;7071// Restrict the input type to types that implement Debug.72fn some_func<T: fmt::Debug>(foo: T) {73    println!("{:?}", foo);74}7576fn main() {77    // Calling the method is still fine, as i32 implements Debug.78    some_func(5i32);7980    // This would fail to compile now:81    // struct WithoutDebug;82    // some_func(WithoutDebug);83}84```8586Rust only looks at the signature of the called function, as such it must87already specify all requirements that will be used for every type parameter.

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.