0

I have a struct with a field 'payload' of Option<T> where T can be one of several primitive integer types. Like so:

pub struct Request<T: MyIntTrait> {
    pub cmd: Cmd,
    pub payload: Option<T>,
    a bunch of other fields...
}

When instantiating this struct with None as its payload obviously type annotations are needed:

let req: Request<u8> = Request { cmd: Cmd::Get, payload: None, ...}

or like this:

let req = Request { cmd: Cmd::Get, payload: None::<u8>, ...}

This makes for a very unergonomic api that is counterintuitive to use. Has anybody got an idea how to get around this or will I just have to live with it?

PaulSimon
  • 35
  • 1
  • 4

1 Answers1

1

Unless the T can be inferred somewhere else, you have to specify it somehow. You could specify a default for the type argument, which may be sufficient in your case:

pub struct Request<T: MyIntTrait = u8>
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • Perfect! Didn't know it's possible to set a default for a type parameter. This solves my problem. Thank you! – PaulSimon May 13 '23 at 13:11
  • 1
    This doesn't disable inference anywhere, and this is effectively unuseful because you will still need to specify the type as `Request` (`let x: Request = Request { ... }`), only a minor difference, or `let x = Request::<> { ... }`. – Chayim Friedman May 13 '23 at 18:04
  • @ChayimFriedman Yeah, true. I noticed as well. But at least one doesn't have to specify the type of "None" anymore which at least to me seems very counterintuitive. – PaulSimon May 13 '23 at 18:38
  • @PaulSimon I don't understand what you mean. – Chayim Friedman May 13 '23 at 18:40
  • @ChayimFriedman Well, I presented just a simplified example to demonstrate the problem. In my real code there is another const generic parameter corresponding to the size of T. Then I needed to write ```let req: Request = Request { payload: None, ... } ```. I just found that to be a bit awkward - a None value of type u16 and size 2... – PaulSimon May 13 '23 at 22:27
  • @ChayimFriedman Hmm, there was an example I constructed where inference appeared to not work correctly when I extracted a variable. I'm wondering now if it was a spurious error from my IDE because I can no longer duplicate it. – cdhowie May 14 '23 at 00:03