Need to implement trait to allow bincode serialize dynamic types

I have a function which uses bincode crate:

pub fn write_vector_to_file<N>(vector: N, file_path: &str) -> Result<(), std::io::Error> {
    let encoded = bincode::serialize(&vector)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
    let mut file = File::create(file_path)?;
    file.write_all(&encoded)?;

    Ok(())
}

I use it to write my Vec (or Vec<Vec> and so on) to the file.
But since I need dynamic type, compiler asks me to add some traits:

35  |     let encoded = bincode::serialize(&vector)
    |                   ------------------ ^^^^^^^ the trait `serde::ser::Serialize` is not implemented for `N`

I do not want to install whole library (serde) only because I need a trait. Does it exist any alternative solution ?

You already have serde as an indirect dependency (or you wouldn't be getting errors about it).

Serialize being implemented is a requirement for that function.

1 Like

Your code already depends on serde transitively via bincode. Adding the dependency to your own Cargo.toml won't cost anything more.

3 Likes

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.