Rust:用于指定性状实现类型的便利性语法?

发布于 2025-02-10 15:05:00 字数 700 浏览 0 评论 0原文

使用结构s考虑以下代码,并具有约束的通用类型参数idxiDx的默认值。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌能量女王 2025-02-17 15:05:00

没有内置的语法,但是您可以使用宏来制作一个语法:

macro_rules! s_impl {
    ( $($t:path => $i:tt)+ ) => {
        $(impl<Idx: Unsigned + PrimInt> $t for S<Idx> $i)+
    }
}

然后您可以做:

s_impl!(
    Clone => {
        fn clone(&self) -> Self {
            S {}
        }
    }
    PartialEq => {
        fn eq(&self, rhs: &Self) -> bool {
            true
        }
    }
);

There isn't a syntax built in, but you can make one yourself using macros:

macro_rules! s_impl {
    ( $($t:path => $i:tt)+ ) => {
        $(impl<Idx: Unsigned + PrimInt> $t for S<Idx> $i)+
    }
}

Then you can do:

s_impl!(
    Clone => {
        fn clone(&self) -> Self {
            S {}
        }
    }
    PartialEq => {
        fn eq(&self, rhs: &Self) -> bool {
            true
        }
    }
);
别低头,皇冠会掉 2025-02-17 15:05:00

@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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文