Home > OS >  Generic function problems
Generic function problems

Time:11-11

I'm playing a bit with generic functions after reading the docs and some examples but seem it seems I can't make them work. Here is what I'm trying to do:

pub fn read_uint<T>(buffer: &Vec<u8>, from: &mut usize, consume_data: bool) -> Option<T>
where
    T: num_traits::Unsigned,
{
    const BYTES_TO_READ:usize = core::mem::size_of::<T>();
    ... 
}

and I'm calling the function with :

let o: u8 = read_uint(buffer, from, false).unwrap();

First of all, how does read_uint infer T type? Is it infering it from the left side of the assignment?

I expected the call to be something like:

let o: u8 = read_uint<u8>(buffer, from, false).unwrap();

The second problem is with the read_uint function itself:

size_of::<T>() is giving the error: "can't use generic parameters from outer function". I have been reading about this error too but couldn't make my head around it.

CodePudding user response:

The problem is that you are making a const depend on a generic argument. This won't work because the value of a constant must be the same for each call to the function, but T could be different each time.

You can easily fix it by changing it to a normal variable binding instead:

pub fn read_uint<T>(buffer: &[u8], from: &mut usize, consume_data: bool) -> Option<T>
where
    T: num_traits::Unsigned,
{
    let bytes_to_read = core::mem::size_of::<T>();
    ...
}
  • Related