Reputation: 8457
struct MyStruct<T: MyTrait> {
inner: T,
}
impl<T: MyTrait> MyStruct<T> {
const MYCONST: u32 = 42;
pub fn x() {
println!("x!");
}
}
pub trait MyTrait {}
Accessing either MYCONST
or x()
requires a trait. If none are provided, the compiler complains:
error[E0282]: type annotations needed
--> src/main.rs:42:5
|
42 | MyStruct::x();
| ^^^^^^^^^^^ cannot infer type for `T`
or
error[E0282]: type annotations needed
--> src/main.rs:42:20
|
42 | println!("{}", MyStruct::MYCONST);
| ^^^^^^^^^^^^^^^^^ cannot infer type for `T`
Is there a way to tell the compiler to ignore the need for type annotations here?
Upvotes: 0
Views: 660
Reputation: 23264
In answer to "Why is the type annotation needed?" consider the following code:
struct MyStruct<T> {
inner: T,
}
impl MyStruct<i32> {
const MYCONST: u32 = 42;
pub fn x() {
println!("i32!");
}
}
impl MyStruct<i64> {
const MYCONST: u32 = 64;
pub fn x() {
println!("i64!");
}
}
fn main() {
MyStruct::x();
}
Should it print i32
or i64
?
Upvotes: 3
Reputation: 430554
The type annotations are needed — there is no type called MyStruct
. This has nothing to do with traits, either:
struct MyStruct<T> {
inner: T,
}
impl<T> MyStruct<T> {
const MYCONST: u32 = 42;
pub fn x() {
println!("x!");
}
}
fn main() {
MyStruct::x();
}
error[E0282]: type annotations needed
--> src/main.rs:14:6
|
14 | MyStruct::x();
| ^^^^^^^^^^^ cannot infer type for type parameter `T`
A type definition with a generic isn't actually a type, it's a type constructor. You must fill in the generics to get a type in order to access associated items.
Upvotes: 3