]>
Commit | Line | Data |
---|---|---|
60c5eb7d XL |
1 | A struct without a field containing an unsized type cannot implement |
2 | `CoerceUnsized`. An [unsized type][1] is any type that the compiler | |
3 | doesn't know the length or alignment of at compile time. Any struct | |
4 | containing an unsized type is also unsized. | |
5 | ||
6 | [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait | |
7 | ||
8 | Example of erroneous code: | |
9 | ||
10 | ```compile_fail,E0374 | |
11 | #![feature(coerce_unsized)] | |
12 | use std::ops::CoerceUnsized; | |
13 | ||
14 | struct Foo<T: ?Sized> { | |
15 | a: i32, | |
16 | } | |
17 | ||
18 | // error: Struct `Foo` has no unsized fields that need `CoerceUnsized`. | |
19 | impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> | |
20 | where T: CoerceUnsized<U> {} | |
21 | ``` | |
22 | ||
23 | `CoerceUnsized` is used to coerce one struct containing an unsized type | |
24 | into another struct containing a different unsized type. If the struct | |
25 | doesn't have any fields of unsized types then you don't need explicit | |
26 | coercion to get the types you want. To fix this you can either | |
27 | not try to implement `CoerceUnsized` or you can add a field that is | |
28 | unsized to the struct. | |
29 | ||
30 | Example: | |
31 | ||
32 | ``` | |
33 | #![feature(coerce_unsized)] | |
34 | use std::ops::CoerceUnsized; | |
35 | ||
36 | // We don't need to impl `CoerceUnsized` here. | |
37 | struct Foo { | |
38 | a: i32, | |
39 | } | |
40 | ||
41 | // We add the unsized type field to the struct. | |
42 | struct Bar<T: ?Sized> { | |
43 | a: i32, | |
44 | b: T, | |
45 | } | |
46 | ||
47 | // The struct has an unsized field so we can implement | |
48 | // `CoerceUnsized` for it. | |
49 | impl<T, U> CoerceUnsized<Bar<U>> for Bar<T> | |
50 | where T: CoerceUnsized<U> {} | |
51 | ``` | |
52 | ||
53 | Note that `CoerceUnsized` is mainly used by smart pointers like `Box`, `Rc` | |
54 | and `Arc` to be able to mark that they can coerce unsized types that they | |
55 | are pointing at. |