I have a trait with specific bounds, for which I want to provide a default implementation of bar()
, as shown in the minimal example below. However, I’m getting an unexpected error E0308. It seems that Rust either forgets that the primitive type i32
implements Mul<i32>
and ignores the explicit type of the local variable a
, or ignores the Output = i32
part of trait Foo: Sized + Add<i32, Output = i32>...
Rust playground
use std::ops::{Add, Mul};
trait Foo: Sized + Add<i32, Output = i32>
where
i32: Mul<Self>,
{
fn bar(self) -> i32 {
let a: i32 = self + 0;
a * 1
}
}
The error I’m getting:
error[E0308]: mismatched types
--> src/lib.rs:10:13
|
3 | trait Foo: Sized + Add<i32, Output = i32>
| ----------------------------------------- expected this type parameter
...
10 | a * 1
| ^ expected type parameter `Self`, found integer
|
= note: expected type parameter `Self`
found type `{integer}`
error[E0308]: mismatched types
--> src/lib.rs:10:9
|
7 | fn bar(self) -> i32 {
| --- expected `i32` because of return type
...
10 | a * 1
| ^^^^^ expected `i32`, found associated type
|
= note: expected type `i32`
found associated type `<i32 as Mul<Self>>::Output`
= help: consider constraining the associated type `<i32 as Mul<Self>>::Output` to `i32`
= note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html
For more information about this error, try `rustc --explain E0308`.
Adding Mul<i32>
to the trait bounds solves the issue, but I don’t understand why since i32
implements it anyway.
use std::ops::{Add, Mul};
trait Foo: Sized + Add<i32, Output = i32>
where
i32: Mul<Self> + Mul<i32>,
{
fn bar(self) -> i32 {
let a: i32 = self + 0;
a * 1
}
}
cosum is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.