0

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

  • What is this `get_item` method used for? – Lambda Fairy Jun 08 '20 at 05:27
  • @LambdaFairy to get the value of the item in the structs. If there is any other way to make it mroe simple, I would love to know! thank you. I need the get_struct_values function to be generic because I'm gonna provide it with different kind of structs – Christopher Tok Jun 08 '20 at 05:28
  • Yes, I understand what the code does, but what is the broader problem that you're trying to solve? There are many ways to make this compile, but I have no idea which is best from the information I'm given. – Lambda Fairy Jun 08 '20 at 05:32
  • @LambdaFairy I am building a microservice using actix-web. So there are 2 API using the same kind of validation method. The function that receive generic struct parameter should be the validation function, because it receives different kind of request body. i want to check from db inside the function that does the validation. I will write here for you – Christopher Tok Jun 08 '20 at 05:40
  • `code fn validate(object:T, session:&sqlx::mysql::MySqlPool) where T:GetItem{ let _ = sqlx::query!("SELECT * from users where phone_number = ?",object.get_item("phone_number")).find_one(session).await?; } ` – Christopher Tok Jun 08 '20 at 05:40
  • 2
    You probably want an associated type instead of a generic parameter: https://stackoverflow.com/questions/32059370/when-is-it-appropriate-to-use-an-associated-type-versus-a-generic-type – Jmb Jun 08 '20 at 07:01
  • Side recommendations: naming conventions in Rust are UpperCamelCase for struct names; and don't forget to format your code properly using rustfmt. – E_net4 Jun 08 '20 at 10:49

0 Answers0