File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -1033,6 +1033,47 @@ fn main() {
10331033 some_func(5i32); // ok!
10341034}
10351035```
1036+
1037+ Or in a generic context, an erroneous code example would look like:
1038+ ```compile_fail
1039+ fn some_func<T>(foo: T) {
1040+ println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
1041+ // implemented for the type `T`
1042+ }
1043+
1044+ fn main() {
1045+ // We now call the method with the i32 type,
1046+ // which *does* implement the Debug trait.
1047+ some_func(5i32);
1048+ }
1049+ ```
1050+
1051+ Note that the error here is in the definition of the generic function: Although
1052+ we only call it with a parameter that does implement `Debug`, the compiler
1053+ still rejects the function: It must work with all possible input types. In
1054+ order to make this example compile, we need to restrict the generic type we're
1055+ accepting:
1056+ ```
1057+ use std::fmt;
1058+
1059+ // Restrict the input type to types that implement Debug.
1060+ fn some_func<T: fmt::Debug>(foo: T) {
1061+ println!("{:?}", foo);
1062+ }
1063+
1064+ fn main() {
1065+ // Calling the method is still fine, as i32 implements Debug.
1066+ some_func(5i32);
1067+
1068+ // This would fail to compile now:
1069+ // struct WithoutDebug;
1070+ // some_func(WithoutDebug);
1071+ }
1072+
1073+ Rust only looks at the signature of the called function, as such it must
1074+ already specify all requirements that will be used for every type parameter.
1075+ ```
1076+
10361077"## ,
10371078
10381079E0281 : r##"
You can’t perform that action at this time.
0 commit comments