]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0376.md
Rollup merge of #92310 - ehuss:rustdoc-ice, r=estebank
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0376.md
1 `CoerceUnsized` was implemented on something that isn't a struct.
2
3 Erroneous code example:
4
5 ```compile_fail,E0376
6 #![feature(coerce_unsized)]
7 use std::ops::CoerceUnsized;
8
9 struct Foo<T: ?Sized> {
10     a: T,
11 }
12
13 // error: The type `U` is not a struct
14 impl<T, U> CoerceUnsized<U> for Foo<T> {}
15 ```
16
17 `CoerceUnsized` can only be implemented for a struct. Unsized types are
18 already able to be coerced without an implementation of `CoerceUnsized`
19 whereas a struct containing an unsized type needs to know the unsized type
20 field it's containing is able to be coerced. An [unsized type][1]
21 is any type that the compiler doesn't know the length or alignment of at
22 compile time. Any struct containing an unsized type is also unsized.
23
24 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
25
26 The `CoerceUnsized` trait takes a struct type. Make sure the type you are
27 providing to `CoerceUnsized` is a struct with only the last field containing an
28 unsized type.
29
30 Example:
31
32 ```
33 #![feature(coerce_unsized)]
34 use std::ops::CoerceUnsized;
35
36 struct Foo<T> {
37     a: T,
38 }
39
40 // The `Foo<U>` is a struct so `CoerceUnsized` can be implemented
41 impl<T, U> CoerceUnsized<Foo<U>> for Foo<T> where T: CoerceUnsized<U> {}
42 ```
43
44 Note that in Rust, structs can only contain an unsized type if the field
45 containing the unsized type is the last and only unsized type field in the
46 struct.