The following code does not do what you expect
impl Foo for Bar {
fn foo<u8>(&self) -> u8 {
self.b
}
}
It introduces a generic type called u8
which shadows the concrete type u8
. Your function would be 100% the same as
impl Foo for Bar {
fn foo<T>(&self) -> T {
self.b
}
}
Which cannot work in this case because T
, chosen by the caller of foo
, isn't guaranteed to be u8
.
To solve this problem in general, choose generic type names that do not conflict with concrete type names. Remember that the function signature in the implementation has to match the signature in the trait definition.
To solve the issue presented, where you wish to fix the generic type as a specific value, you can move the generic parameter to the trait, and implement the trait just for u8
:
trait Foo<T> {
fn foo(&self) -> T;
}
struct Bar {
b: u8,
}
impl Foo<u8> for Bar {
fn foo(&self) -> u8 {
self.b
}
}
Or you can use an associated trait, if you never want multiple Foo
impls for a specific type (thanks @MatthieuM):
trait Foo {
type T;
fn foo(&self) -> T;
}
struct Bar {
b: u8,
}
impl Foo for Bar {
type T = u8;
fn foo(&self) -> u8 {
self.b
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…