I am learning to make functions with generic types but I have been stuck for a few hours with this error that says cannot infer type for type parameter 'X'
. It is assumed that in my implementation I have already defined the types that X
and Y
will have.
pub struct Generate<X, Y> {
pub data_type: X,
pub data_config: Y,
}
impl<X, Y> Generate<X, Y> {
pub fn new_bi() -> Generate<u16, String> {
Generate {
data_type: 10,
data_config: String::from("Hello"),
}
}
pub fn new_an() -> Generate<String, u16> {
Generate {
data_type: String::from("Hello"),
data_config: 10,
}
}
}
fn main() {
let y = Generate::new_bi(); // ERROR HERE
let y: Generate<u16, String> = Generate::new_bi(); // I tried this but it didn't work
}
error[E0282]: type annotations needed
--> src/lib.rs:22:13
|
22 | let y = Generate::new_bi(); // ERROR HERE
| ^^^^^^^^^^^^^^^^ cannot infer type for type parameter `X`
error[E0282]: type annotations needed
--> src/lib.rs:23:36
|
23 | let y: Generate<u16, String> = Generate::new_bi(); // I tried this but it didn't work
| ^^^^^^^^^^^^^^^^ cannot infer type for type parameter `X`
You can make specific implementations depending on the types:
pub struct Generate<X, Y> {
pub data_type: X,
pub data_config: Y,
}
impl Generate<u16, String> {
pub fn new_bi() -> Generate<u16, String> {
Generate {
data_type: 10,
data_config: String::from("Hello"),
}
}
}
impl Generate<String, u16> {
pub fn new_an() -> Generate<String, u16> {
Generate {
data_type: String::from("Hello"),
data_config: 10,
}
}
}
fn main() {
let y = Generate::new_bi();
let y: Generate<u16, String> = Generate::new_bi();
let x = Generate::new_an();
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With