I'm trying to return a statically dispatched trait in a function declared in the same trait, but the compiler seems unable to map between the trait type and the concrete type.
Example:
trait Money {
fn trade<M>(&self) -> M
where M: Money;
}
impl Money for Dollar {
fn trade<M>(&self) -> M
where M: Money
{
Dollar { amount: self.amount / 2 }
}
}
You can try out the complete example here: http://is.gd/alQGv0
The compiler's in the right here. What you've told it is that you're implementing a function trade
which, for any M
the caller cares to use (so long as it implements Money
), you will return an instance of that M
. And then you go and try to return a Dollar
. What if M
isn't Dollar
?
What you probably want here, from context, is the following:
trait Money {
fn trade(&self) -> Self;
}
struct Dollar {
amount: usize,
}
impl Money for Dollar {
fn trade(&self) -> Dollar
{
Dollar { amount: self.amount / 2 }
}
}
fn main() {
let x = Dollar { amount: 10 };
println!("{}", x.trade().amount);
}
Here, the trade
function is changed to always return the type it's implemented for; within the Money
trait definition, that's Self
. When you're talking about a specific implementation, it's the implementation type (so it's Dollar
when you're implementing Money
for Dollar
).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments