about summary refs log tree commit diff
diff options
context:
space:
mode:
authorSteve Klabnik <steve@steveklabnik.com>2015-08-05 12:58:49 -0400
committerSteve Klabnik <steve@steveklabnik.com>2015-08-18 11:27:02 -0400
commitce1bdc729338d723faf2de9410f890c5d00e5bf6 (patch)
tree49ad036b88a491186ec529e7963b60a5cb3f23f9
parentd03456183e85fe7bd465bbe7c8f67885a2528444 (diff)
downloadrust-ce1bdc729338d723faf2de9410f890c5d00e5bf6.tar.gz
rust-ce1bdc729338d723faf2de9410f890c5d00e5bf6.zip
Add object safety to TRPL
Fixes #26938
-rw-r--r--src/doc/trpl/trait-objects.md38
1 files changed, 38 insertions, 0 deletions
diff --git a/src/doc/trpl/trait-objects.md b/src/doc/trpl/trait-objects.md
index f9dbc143c82..8127b0898c4 100644
--- a/src/doc/trpl/trait-objects.md
+++ b/src/doc/trpl/trait-objects.md
@@ -300,3 +300,41 @@ let y = TraitObject {
 // y.method();
 (y.vtable.method)(y.data);
 ```
+
+## Object Safety
+
+Not every trait can be used to make a trait object. For example, vectors implement
+`Clone`, but if we try to make a trait object:
+
+```ignore
+let v = vec![1, 2, 3];
+let o = &v as &Clone;
+```
+
+We get an error:
+
+```text
+error: cannot convert to a trait object because trait `core::clone::Clone` is not object-safe [E0038]
+let o = &v as &Clone;
+        ^~
+note: the trait cannot require that `Self : Sized`
+let o = &v as &Clone;
+        ^~
+```
+
+The error says that `Clone` is not ‘object-safe’. Only traits that are
+object-safe can be made into trait objects. A trait is object-safe if both of
+these are true:
+
+* the trait does not require that `Self: Sized`
+* all of its methods are object-safe
+
+So what makes a method object-safe? Each method must require that `Self: Sized`
+or all of the following:
+
+* must not have any type parameters
+* must not use `Self`
+
+Whew! As we can see, almost all of these rules talk about `Self`. A good intuition
+is “except in special circumstances, if your trait’s method uses `Self`, it is not
+object-safe.”