How to serialize several objects with one function

Hi,

I would like to serialize Strings, str, structures, Vec, etc. into byte streams and with one function. Is this even possible?

example:

pub struct AS<T> {
    x: T,
}

pub struct A {
    x: i32,
}

fn make_bytes<T>(payload: T) // I would like my payload to be Vec or String or structure or  ...
{
    let bytes = bincode::serialize(&payload).unwrap();
    println!("{:?}", bytes);
}

In order to overload make_bytes I tried to do the same as in c++ but it did not work. So i guess my first question is is is possible to overload functions and how? And my second question is, if I use generics I get that serialize cannot work with them... Could someone please help and workout a small example for me so I ca study it ?

thnx

Since bincode::serialize takes any Serde serializable type, you can implement serde::Serialize for the types you want to serialize (most basic types already implement it,) then you can make the function take a T: Serialize, like so:

use serde::Serialize;

#[derive(Serialize)]
pub struct AS<T> {
    x: T,
}

fn make_bytes<T: Serialize>(payload: T) {
    let bytes = bincode::serialize(&payload).unwrap();
    println!("{:?}", bytes);
}
3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.