In Chapter 10 of the rust lang book there is a an example of static dispatch that looks like so:
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &i in list {
if i > largest {
largest = i;
}
}
largest
}
I'm trying to re-implement the same example using dynamic dispatch, as described in chapter 17. My best attempt so far:
fn largest_dyn(list: &[Box<dyn PartialOrd<i32>>]) -> Box<dyn PartialOrd<i32>> {
let mut largest = &list[0];
for &i in list {
if *i > **largest {
**largest = *i;
}
}
**largest
}
But this doesn't compile. The error I get is:
expected `i32`, found trait object `dyn PartialOrd`
I have a bunch of questions I was hoping someone could help with:
- Why does the above not compile? It seems that I'm dereferencing left and right sides the same number of times, yet one is an
i32
but another one is adyn trait object
? - The compiler forced me to put
<i32>
afterdyn PartialOrd
to even get this far. I don't get it - wasn't the purpose of trait objects specifically that they didn't require you to specify a type, and only a trait? Why am I forced to put a type here? - The original function actually implements two traits:
PartialOrd
andCopy
. I couldn't find a way to do that withBox<>
-Box<dyn PartialOrd + dyn Copy>
doesn't seem to work. Is there a way to have a trait object for multiple traits at once?