From 9624b68207c8c8d216e6e981088cb54d46aa1152 Mon Sep 17 00:00:00 2001 From: Kamal Marhubi Date: Fri, 22 Jan 2016 14:37:37 -0500 Subject: [PATCH 1/2] book: Clarify that trait or type must be in same crate as impl --- src/doc/book/traits.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/doc/book/traits.md b/src/doc/book/traits.md index d40689190e7fe..2101533af51c3 100644 --- a/src/doc/book/traits.md +++ b/src/doc/book/traits.md @@ -277,11 +277,15 @@ This will compile without error. This means that even if someone does something bad like add methods to `i32`, it won’t affect you, unless you `use` that trait. -There’s one more restriction on implementing traits: either the trait, or the -type you’re writing the `impl` for, must be defined by you. So, we could -implement the `HasArea` type for `i32`, because `HasArea` is in our code. But -if we tried to implement `ToString`, a trait provided by Rust, for `i32`, we could -not, because neither the trait nor the type are in our code. +There’s one more restriction on implementing traits: either the trait +or the type you’re implementing it for must be defined by you. Or more +precisely, one of them must be defined in the same crate as the `impl` +you're writing. + +So, we could implement the `HasArea` type for `i32`, because we defined +`HasArea` in our code. But if we tried to implement `ToString`, a trait +provided by Rust, for `i32`, we could not, because neither the trait nor +the type are defined in our crate. One last thing about traits: generic functions with a trait bound use ‘monomorphization’ (mono: one, morph: form), so they are statically dispatched. From a559577c2f2030df89f9f8b245d49e86a4f90d93 Mon Sep 17 00:00:00 2001 From: Kamal Marhubi Date: Fri, 22 Jan 2016 15:18:00 -0500 Subject: [PATCH 2/2] Forward reference crates and modules chapter --- src/doc/book/traits.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/doc/book/traits.md b/src/doc/book/traits.md index 2101533af51c3..2a164077683b2 100644 --- a/src/doc/book/traits.md +++ b/src/doc/book/traits.md @@ -280,7 +280,8 @@ it won’t affect you, unless you `use` that trait. There’s one more restriction on implementing traits: either the trait or the type you’re implementing it for must be defined by you. Or more precisely, one of them must be defined in the same crate as the `impl` -you're writing. +you're writing. For more on Rust's module and package system, see the +chapter on [crates and modules][cm]. So, we could implement the `HasArea` type for `i32`, because we defined `HasArea` in our code. But if we tried to implement `ToString`, a trait @@ -291,6 +292,7 @@ One last thing about traits: generic functions with a trait bound use ‘monomorphization’ (mono: one, morph: form), so they are statically dispatched. What’s that mean? Check out the chapter on [trait objects][to] for more details. +[cm]: crates-and-modules.html [to]: trait-objects.html # Multiple trait bounds