指定泛型参数属于一小类类型 [英] Specifying generic parameter to belong to a small set of types
问题描述
是否有可能将一个通用参数约束为少数几种类型之一,而又不弄清楚哪些特征可以精确地定义那些类型?例如
Is it possible with to constrain a generic parameter to be one of the select few types without figuring out what traits precisely define those type? e.g.
impl<T> Data<T> where T == u32 || T == u64
有时候,弄清楚要添加到where
的所有特征以获取所需的类型是一件很麻烦的事情,有时,即使由于语义而在语法上有意义,也不允许这种类型.
Sometimes it's tedious to figure out what all traits to add to where
to get the types you want, and sometimes one wouldn't want to allow a type even when it makes syntactic sense because of semantics.
推荐答案
您可以对要支持的类型使用标记特征:
You could use a marker trait for the types you want to support:
trait DataSupported {}
impl DataSupported for u64 {}
impl DataSupported for u32 {}
impl<T> Data<T> where T: DataSupported {}
为 Pavel Strakhov提到的,如果您需要在几个impl
上使用此特征,并且需要其他特征界限,则可以将这些特征作为标记特征的界限,这样可以保留您的impl
简洁:
As Pavel Strakhov mentioned, if you need to use this trait for a few impl
s and you need other trait bounds, then you can just make those traits as bounds of your marker trait instead, which will keep your impl
s terse:
trait DataSupported: Num + Debug {}
这篇关于指定泛型参数属于一小类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!