Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use builtin traits From and PartialOrd for Box object bounds

Tags:

rust

Admittedly, I'm fairly new to Rust, but I love what I'm seeing so far. That said, I'm running into an issue where I'm getting the error:

error: only the builtin traits can be used as closure or object bounds [E0225]
defaults: HashMap<String, Box<Any + From<String> + PartialOrd>>,
                                    ^~~~~~~~~~~~

for the following code:

pub struct Builder {                                                                                                                                                                                                                           
    defaults: HashMap<String, Box<Any + From<String> + PartialOrd>>,                                                                                                                                                                           
    ...
}

If I remove the bound on From I get the same error but for PartialOrd. I don't understand why since I'm fairly certain both From and PartialOrd are builtin traits. Any help would be appreciated.

like image 300
mattforni Avatar asked Mar 14 '23 00:03

mattforni


1 Answers

$ rustc --explain E0225
You attempted to use multiple types as bounds for a closure or trait object.
Rust does not currently support this. A simple example that causes this error:

fn main() {
    let _: Box<std::io::Read+std::io::Write>;
}

Builtin traits are an exception to this rule: it's possible to have bounds of
one non-builtin type, plus any number of builtin types. For example, the
following compiles correctly:

fn main() {
    let _: Box<std::io::Read+Copy+Sync>;
}

PartialOrd and From aren't built-in, they're defined in the standard library. Traits like Copy and Sync are built-in.

You can work around this by defining a new trait with the traits you want as supertraits:

trait MyTrait: Any + From<String> + PartialOrd {}

Then you can provide a blanket impl for all types that implement all of the traits you want (you can specify multiple traits in bounds, but not in trait objects):

impl<T> MyTrait for T where T: Any + From<String> + PartialOrd {}
like image 150
Clark Gaebel Avatar answered Mar 16 '23 00:03

Clark Gaebel