且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

指定泛型参数属于一小类类型

更新时间:2023-09-29 11:42:22

您可以对要支持的类型使用标记特征:

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 impls and you need other trait bounds, then you can just make those traits as bounds of your marker trait instead, which will keep your impls terse:

trait DataSupported: Num + Debug {}