Tell bincode::config() deserialize type


#1

Often, you tell bincode::config() the type for the deserialized object in the ‘let’ statement like in

use bincode::config;

let bytes:[u8; 32]= [0xFF;32];
let unsigned_integer:u64 = config().big_endian().deserialize(&bytes[6…14]).unwrap();

However if you want to use ‘match’ to capture error handling an do the following:

let bytes:[u8; 32]= [0xFF;32];

match config().big_endian().deserialize(&bytes[6…14]) { // supposed to deserialize into u64
Ok(unsigned_integer) => {
let index:usize = (unsigned_integer as usize)-10;
// usefull stuff
}
Err(e1) => {
println!(“Error in bincode deserialization: {:?}”, e1);
}
}

The, of course, the compiler has no way to infer the type of the variable unsigned_integer. How can we solve this?


#2

The Config::deserialize function accepts a type parameter which is the type to deserialize. When not inferable, you can specify it explicitly.

match config().big_endian().deserialize::<u64>(&bytes[6..14]) {
                                       ^^^^^^^

This is called turbofish.


#3

How can find out which type/function has this implemented. To me it does not follow from the description of bincode::config() nor bincode::deserialize()


#4

Almost any function with a type parameter supports this form. Here is Config::deserialize with a type parameter:

pub fn deserialize<'a, T: Deserialize<'a>>(&self, bytes: &'a [u8]) -> Result<T>
                       ^

The exception is if any of the arguments has a type with is impl SomeTrait, in which case turbofish is not supported.


#5

If turbofish is not supported, you can use a temporary variable to tell Rust what type you want.

let config: Result</* your type here */, _> = config().big_endian().deserialize(&bytes[6…14]);
match config { ... }