blob: fa0b615db3936024b334713ecb499bc476cf0499 [file] [view]
Multiple traits were used as bounds in a `dyn` trait object type.
Erroneous code example:
```compile_fail,E0225,edition2024
struct Example {
file: Box<dyn std::io::Read + std::io::Write>,
}
```
Rust does not currently support ad-hoc combinations of traits in one trait
object. There are several exceptions and alternatives:
* Any number of auto traits such as `Send` and `Sync` are permitted to
accompany a single normal trait. For example, the following code is
accepted:
```edition2024
struct Example {
file: Box<dyn std::io::Read + Send + Sync>,
}
```
* Supertraits of the single non-auto trait are permitted and do not need to
be specified explicitly. For example, the following code is permitted,
even though `read_to_string()` is a method of `Read`, not `BufRead`,
because `Read` is a supertrait of `BufRead`.
```edition2024
struct Example {
file: Box<dyn std::io::BufRead>,
}
impl Example {
fn read(mut self, string: &mut String) -> std::io::Result<usize> {
self.file.read_to_string(string)
}
}
```
Therefore, if you are defining traits intended for use as trait objects,
adding supertraits may be a suitable solution for this error.
* If you cannot or should not modify the definition of either trait, you can
instead define a new trait which is implemented for that combination:
```edition2024
trait ReadWrite: std::io::Read + std::io::Write {}
impl<T: std::io::Read + std::io::Write> ReadWrite for T {}
struct Example {
file: Box<dyn ReadWrite>,
}
```