]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0375.md
Rollup merge of #93556 - dtolnay:trailingcomma, r=cjgillot
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0375.md
1 `CoerceUnsized` was implemented on a struct which contains more than one field
2 with an unsized type.
3
4 Erroneous code example:
5
6 ```compile_fail,E0375
7 #![feature(coerce_unsized)]
8 use std::ops::CoerceUnsized;
9
10 struct Foo<T: ?Sized, U: ?Sized> {
11     a: i32,
12     b: T,
13     c: U,
14 }
15
16 // error: Struct `Foo` has more than one unsized field.
17 impl<T, U> CoerceUnsized<Foo<U, T>> for Foo<T, U> {}
18 ```
19
20 A struct with more than one field containing an unsized type cannot implement
21 `CoerceUnsized`. This only occurs when you are trying to coerce one of the
22 types in your struct to another type in the struct. In this case we try to
23 impl `CoerceUnsized` from `T` to `U` which are both types that the struct
24 takes. An [unsized type][1] is any type that the compiler doesn't know the
25 length or alignment of at compile time. Any struct containing an unsized type
26 is also unsized.
27
28 `CoerceUnsized` only allows for coercion from a structure with a single
29 unsized type field to another struct with a single unsized type field.
30 In fact Rust only allows for a struct to have one unsized type in a struct
31 and that unsized type must be the last field in the struct. So having two
32 unsized types in a single struct is not allowed by the compiler. To fix this
33 use only one field containing an unsized type in the struct and then use
34 multiple structs to manage each unsized type field you need.
35
36 Example:
37
38 ```
39 #![feature(coerce_unsized)]
40 use std::ops::CoerceUnsized;
41
42 struct Foo<T: ?Sized> {
43     a: i32,
44     b: T,
45 }
46
47 impl <T, U> CoerceUnsized<Foo<U>> for Foo<T>
48     where T: CoerceUnsized<U> {}
49
50 fn coerce_foo<T: CoerceUnsized<U>, U>(t: T) -> Foo<U> {
51     Foo { a: 12i32, b: t } // we use coercion to get the `Foo<U>` type we need
52 }
53 ```
54
55 [1]: https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait