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 1
1
---
2
2
refs/heads/master: edeb4f1c86cbf6af8ef9874d4b3af50f721ea1b8
3
3
refs/heads/snap-stage3: 1af31d4974e33027a68126fa5a5a3c2c6491824f
4
- refs/heads/try: dbbcb434b12da3465037ff2bbd16b1060afa3469
4
+ refs/heads/try: 572526be2742e368cd522709eccd35df6428fd64
5
5
refs/tags/release-0.1: 1f5c5126e96c79d22cb7862f75304136e204f105
6
6
refs/tags/release-0.2: c870d2dffb391e14efb05aa27898f1f6333a9596
7
7
refs/tags/release-0.3: b5f0d0f648d9a6153664837026ba1be43d3e2503
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