Type annotations needed for none variant – ergonomics

huangapple go评论52阅读模式
英文:

Type annotations needed for none variant - ergonomics

问题

我有一个结构体,其中有一个名为 'payload' 的字段,其类型为 Option<T>,其中 T 可以是多种原始整数类型之一。像这样:

pub struct Request<T: MyIntTrait> {
    pub cmd: Cmd,
    pub payload: Option<T>,
    其他一些字段...
}

当使用 None 实例化此结构体时,显然需要类型注释:

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

或者像这样:

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

这使得 API 不够人性化,使用起来很反直觉。有人有什么办法可以解决这个问题,还是我只能忍受它?

英文:

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?

答案1

得分: 1

除非T可以在其他地方被推断出来,否则你必须以某种方式指定它。在你的情况下,你可以为类型参数指定一个默认值,这可能足够了:

pub struct Request<T: MyIntTrait = u8>
英文:

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&lt;T: MyIntTrait = u8&gt;

huangapple
  • 本文由 发表于 2023年5月13日 20:23:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242707.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定