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