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 Impl
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
}
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();// ERROR HERE
let y: Generate<u16,String> = Generate::new_bi();//I tried this but it didn't work
let x = Generate::new_an();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.