File tree Expand file tree Collapse file tree 3 files changed +40
-2
lines changed Expand file tree Collapse file tree 3 files changed +40
-2
lines changed Original file line number Diff line number Diff line change @@ -23,7 +23,7 @@ refs/tags/0.9: 36870b185fc5f5486636d4515f0e22677493f225
23
23
refs/tags/0.10: ac33f2b15782272ae348dbd7b14b8257b2148b5a
24
24
refs/tags/0.11.0: e1247cb1d0d681be034adb4b558b5a0c0d5720f9
25
25
refs/tags/0.12.0: f0c419429ef30723ceaf6b42f9b5a2aeb5d2e2d1
26
- refs/heads/beta: dbbcb434b12da3465037ff2bbd16b1060afa3469
26
+ refs/heads/beta: 572526be2742e368cd522709eccd35df6428fd64
27
27
refs/tags/1.0.0-alpha: e42bd6d93a1d3433c486200587f8f9e12590a4d7
28
28
refs/heads/tmp: 370fe2786109360f7c35b8ba552b83b773dd71d6
29
29
refs/tags/1.0.0-alpha.2: 4c705f6bc559886632d3871b04f58aab093bfa2f
Original file line number Diff line number Diff line change @@ -300,3 +300,41 @@ let y = TraitObject {
300
300
// y.method();
301
301
(y.vtable.method)(y.data);
302
302
```
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.”
Original file line number Diff line number Diff line change 112
112
//! // 7
113
113
//! // +-----------------+
114
114
//! // | |
115
- //! // v 1 2 |
115
+ //! // v 1 2 | 2
116
116
//! // 0 -----> 1 -----> 3 ---> 4
117
117
//! // | ^ ^ ^
118
118
//! // | | 1 | |
You can’t perform that action at this time.
0 commit comments