Rust:用于指定性状实现类型的便利性语法?
使用结构s
考虑以下代码,并具有约束的通用类型参数idx
和iDx
的默认值。
use num::{PrimInt, Unsigned};
struct S<Idx = u32>
where
Idx: Unsigned + PrimInt, {
// ... Some fields
}
impl<Idx: Unsigned + PrimInt> Clone for S<Idx> {
fn clone(&self) -> Self {
S {}
}
}
impl<Idx: Unsigned + PrimInt> Eq for S<Idx> {
fn eq(&self, rhs: &Self) -> bool {
true
}
}
我想为s
实现一堆特征,但是我发现始终指定IDX
键入参数乏味的约束。如果我在特征实现上不指定iDx
,则代码编译,但仅具有idx = u32
的实现。
是否有一些便利性语法,我不必始终指定idx:unsigned + primint
,但仍然正确地实现了这些特征?
Consider the following code with a struct S
with a constrained generic type parameter Idx
and a default value for Idx
.
use num::{PrimInt, Unsigned};
struct S<Idx = u32>
where
Idx: Unsigned + PrimInt, {
// ... Some fields
}
impl<Idx: Unsigned + PrimInt> Clone for S<Idx> {
fn clone(&self) -> Self {
S {}
}
}
impl<Idx: Unsigned + PrimInt> Eq for S<Idx> {
fn eq(&self, rhs: &Self) -> bool {
true
}
}
I would like to implement a bunch of traits for S
, but I find always specifying the constraints for the Idx
type parameter tedious. If I don't specify Idx
on a trait implementation, the code compiles but only has an implementation for Idx = u32
.
Is there some convenience syntax where I don't have to specify the Idx: Unsigned + PrimInt
all the time but still correctly implements the traits?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有内置的语法,但是您可以使用宏来制作一个语法:
然后您可以做:
There isn't a syntax built in, but you can make one yourself using macros:
Then you can do:
@cdhowie的答案是正确的,但我想指出,有一个接受(但尚未实现,截至写作时间)RFC可以允许您省略此类界限 - rfc#2089含义界限。
但是,尚不清楚该功能的形式是什么,因为它是 semver危害。
The answer from @cdhowie is correct, but I would like to point that there is an accepted (but not yet implemented, as of time of writing) RFC to allow you to omit such bounds - RFC #2089 Implied Bounds.
It is not yet clear what will be the form of the feature, though, because it is a semver hazard.