Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to invoke a generic function in rust

Now I am define a generic function in rust like this:

pub fn fav_music_query<T>() -> String {
    use crate::model::diesel::rhythm::rhythm_schema::favorites::dsl::*;
    let connection = config::establish_music_connection();
    let query = favorites.filter(like_status.eq(1)).paginate(1).per_page(10);
    let query_result = query.load_and_count_pages::<Favorites>(&connection).unwrap();

    return "ok".to_string();
}

now I want to invoke this function in the outer function, this is my outer function code which to invoke the generic function:

let dashboards = fav_music_query();

and shows error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error[E0282]: type annotations needed
  --> src/biz/home/home_controller.rs:12:22
   |
12 |     let dashboards = fav_music_query();
   |                      ^^^^^^^^^^^^^^^ cannot infer type for type parameter `T` declared on the function `fav_music_query`

let dashboards = fav_music_query<>();

what should I do to invoke this function? I tried this way:

let dashboards = fav_music_query<Favorites>();

it seems did not work.

>Solution :

for that you can use the turbofish operator ::<>:

let dashboards = fav_music_query::<Favorites>();

But you don’t even use the generic in your function, I guess you forgot to replace query.load_and_count_pages::<Favorites>(&connection) with query.load_and_count_pages::<T>(&connection)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading