about summary refs log tree commit diff
diff options
context:
space:
mode:
authorTobias Bucher <tobiasbucher5991@gmail.com>2016-03-31 11:15:36 +0200
committerTobias Bucher <tobiasbucher5991@gmail.com>2016-03-31 11:15:36 +0200
commit10caca24f0052a033cac648884d2393125bc24a3 (patch)
treeb1e981887ae6618c642929690e36cb678072348d
parent30a3849f228833f9dc280120126d16aef3a292ba (diff)
downloadrust-10caca24f0052a033cac648884d2393125bc24a3.tar.gz
rust-10caca24f0052a033cac648884d2393125bc24a3.zip
Improve E0277 error message in a generic context
This now mentions that you can restrict type parameters to be able to
call functions of traits.
-rw-r--r--src/librustc/diagnostics.rs41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/librustc/diagnostics.rs b/src/librustc/diagnostics.rs
index 117b1119c0a..6f06efd0f9f 100644
--- a/src/librustc/diagnostics.rs
+++ b/src/librustc/diagnostics.rs
@@ -1033,6 +1033,47 @@ fn main() {
     some_func(5i32); // ok!
 }
 ```
+
+Or in a generic context, an erroneous code example would look like:
+```compile_fail
+fn some_func<T>(foo: T) {
+    println!("{:?}", foo); // error: the trait `core::fmt::Debug` is not
+                           //        implemented for the type `T`
+}
+
+fn main() {
+    // We now call the method with the i32 type,
+    // which *does* implement the Debug trait.
+    some_func(5i32);
+}
+```
+
+Note that the error here is in the definition of the generic function: Although
+we only call it with a parameter that does implement `Debug`, the compiler
+still rejects the function: It must work with all possible input types. In
+order to make this example compile, we need to restrict the generic type we're
+accepting:
+```
+use std::fmt;
+
+// Restrict the input type to types that implement Debug.
+fn some_func<T: fmt::Debug>(foo: T) {
+    println!("{:?}", foo);
+}
+
+fn main() {
+    // Calling the method is still fine, as i32 implements Debug.
+    some_func(5i32);
+
+    // This would fail to compile now:
+    // struct WithoutDebug;
+    // some_func(WithoutDebug);
+}
+
+Rust only looks at the signature of the called function, as such it must
+already specify all requirements that will be used for every type parameter.
+```
+
 "##,
 
 E0281: r##"