If I have 2 structs
struct first {
item_a: String,
item_b: i32
}
struct second{
item_a: String,
item_b: i32,
item_c: u64
}
I want to get the value of each struct using generic function
the compiler said :
return Some(self.item_a.clone());
^^^^^^^^^^^^^^^^^^^ expected type parameter `T`, found struct `std::string::String`
Any idea how to do get struct value inside a generic function?
Update: i got the answer!
#[derive(Debug)]
struct first<T> {
item_a: T
}
trait GetItem {
type Output;
fn get_item(&self,key:&str)->Option<Self::Output>;
}
impl<T:std::clone::Clone> GetItem for first<T>{
type Output=T;
fn get_item(&self,key:&str) -> Option<Self::Output>{
match key{
"item_a"=>{
return Some(self.item_a.clone());
}
_ => {
return None;
}
}
}
}
fn get_struct_values<T>(object:T)
where T:GetItem<Output=String>{
println!("this is item a = {:?}",object.get_item("item_a"));
}
fn main(){
get_struct_values(first{item_a:String::from("asd")});
}
Tags: rust trait impl generic type output