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();

The problem I'm having is:

error[E0283]: type annotations needed
   --> src\
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\\serde-1.0.125\src\de\
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>>
    T: DeserializeOwned,
    let reader = BufReader::new(File::open(file_name)?);

bincode::deserialize_from requires DeserializeOwned.

That worked, thank you very much! :grinning:

See also:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.