Serde: deserialize generic data type

Hello, I'm trying to write a "wrapper" function that will be used to de-serialize different data types with Serde (bincode) from different files.

Here's my code:

pub fn deserialize_object_from_file<'a, T: Deserialize<'a> + for<'de> Deserialize<'de>>(
    file_name: String,
) -> T {
    let mut file = File::open(&file_name).expect(&format!("Couldn't open file {}",&file_name));
    let reader = BufReader::new(file);
    let deserialized_object = bincode::deserialize_from(reader).unwrap();
    deserialized_object
}

The problem I'm having is:

error[E0283]: type annotations needed
   --> src\serialization.rs:27:44
    |
27  | pub fn deserialize_object_from_file<'a, T: Deserialize<'a> + for<'de> Deserialize<'de>>(
    |                                            ^^^^^^^^^^^^^^^ cannot infer type for type parameter `T`
    | 
   ::: C:\Users\hoped\.cargo\registry\src\github.com-1ecc6299db9ec823\serde-1.0.125\src\de\mod.rs:530:1
    |
530 | pub trait Deserialize<'de>: Sized {
    | --------------------------------- required by this bound in `Deserialize`
    |
    = note: cannot satisfy `T: Deserialize<'a>`

One simple solution could be to use a separate function for each data type, but I think it can be done better. Can anyone help? Thank you in advance!

You probabably want something more like this :

use serde::de::DeserializeOwned;
use std::error::Error;
use std::fs::File:
use std::io::BufReader;

fn from_file<T>(file_name: &str) -> Result<T, Box<dyn Error>>
where
    T: DeserializeOwned,
{
    let reader = BufReader::new(File::open(file_name)?);
    Ok(bincode::deserialize_from(reader)?)
}

bincode::deserialize_from requires DeserializeOwned.

That worked, thank you very much! :grinning:

See also: