Error code E0225
Multiple traits were used as bounds in a dyn trait object type.
Erroneous code example:
#![allow(unused)]
fn main() {
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
SendandSyncare permitted to accompany a single normal trait. For example, the following code is accepted: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 ofRead, notBufRead, becauseReadis a supertrait ofBufRead.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:
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>, }