File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff 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.”
You can’t perform that action at this time.
0 commit comments