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