简体   繁体   English

Rust:在 trait 实现上指定类型的便捷语法?

[英]Rust: Convenience syntax for specifying types on trait implementations?

Consider the following code with a struct S with a constrained generic type parameter Idx and a default value for Idx .考虑以下代码,其结构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
    }
}

I would like to implement a bunch of traits for S , but I find always specifying the constraints for the Idx type parameter tedious.我想为S实现一堆特征,但我发现总是为Idx类型参数指定约束很乏味。 If I don't specify Idx on a trait implementation, the code compiles but only has an implementation for Idx = u32 .如果我没有在 trait 实现上指定Idx ,则代码会编译,但只有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?是否有一些方便的语法,我不必一直指定Idx: Unsigned + PrimInt但仍能正确实现特征?

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
        }
    }
);

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 . @cdhowie 的答案是正确的,但我想指出的是,有一个接受的(但截至撰写本文时尚未实施)RFC 允许您省略此类界限 - RFC #2089 Implied Bounds

It is not yet clear what will be the form of the feature, though, because it is a semver hazard .不过,目前尚不清楚该功能的形式是什么,因为它是一个semver 危险

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM