Camden Narzt
Camden Narzt

Reputation: 2003

How can I specify a type when I assign a generic function to a variable

I'd like to do something conceptually like this: let fun: fn(&mut _) -> Result<u32> = ReadBytesExt::read_u32::<BigEndian>;

But that doesn't work as rust thinks I'm trying to call ReadBytesExt::read_u32 with BigEndian as a type arg and no other arg. (I get a wrong number of args error).

So what do I do, seems like something that rust's type system should allow, since I'm trying to be MORE specific.

Upvotes: 0

Views: 68

Answers (1)

Chris Morgan
Chris Morgan

Reputation: 90712

Values cannot and never will be able to contain bound generics; the concept simply cannot be accomplished due to how monomorphisation works.

Such a thing needs to be done with a wrapping function like this:

fn read_u32_be<R: Read>(&mut r: R) -> byteorder::Result<u32> {
    r.read_u32::<BigEndian>()
}

Upvotes: 1

Related Questions