Skip to content

Commit dc9b74f

Browse files
committed
Auto merge of #27536 - steveklabnik:doc_object_safety, r=alexcrichton
Fixes #26938
2 parents c6291e0 + ce1bdc7 commit dc9b74f

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/doc/trpl/trait-objects.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,3 +300,41 @@ let y = TraitObject {
300300
// y.method();
301301
(y.vtable.method)(y.data);
302302
```
303+
304+
## Object Safety
305+
306+
Not every trait can be used to make a trait object. For example, vectors implement
307+
`Clone`, but if we try to make a trait object:
308+
309+
```ignore
310+
let v = vec![1, 2, 3];
311+
let o = &v as &Clone;
312+
```
313+
314+
We get an error:
315+
316+
```text
317+
error: cannot convert to a trait object because trait `core::clone::Clone` is not object-safe [E0038]
318+
let o = &v as &Clone;
319+
^~
320+
note: the trait cannot require that `Self : Sized`
321+
let o = &v as &Clone;
322+
^~
323+
```
324+
325+
The error says that `Clone` is not ‘object-safe’. Only traits that are
326+
object-safe can be made into trait objects. A trait is object-safe if both of
327+
these are true:
328+
329+
* the trait does not require that `Self: Sized`
330+
* all of its methods are object-safe
331+
332+
So what makes a method object-safe? Each method must require that `Self: Sized`
333+
or all of the following:
334+
335+
* must not have any type parameters
336+
* must not use `Self`
337+
338+
Whew! As we can see, almost all of these rules talk about `Self`. A good intuition
339+
is “except in special circumstances, if your trait’s method uses `Self`, it is not
340+
object-safe.”

0 commit comments

Comments
 (0)