英文:
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<T: MyIntTrait = u8>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论