简体   繁体   English

在 Rust 特征绑定中需要交换操作

[英]Require commutative operation in Rust trait bound

Suppose I have a group of related non-scalar structs with a commutative arithmetic operation defined on them.假设我有一组相关的非标量结构,其中定义了交换算术运算。 For example,例如,

struct Foo {
    a: f64,
    b: f64
}

impl Add<f64> for Foo {
    type Output = Foo;
    
    fn add(self, v: f64) -> Self::Output {
        Foo {
            a: self.a + v,
            b: self.b + v
        }
    }
}

impl Add<Foo> for f64 {
    type Output = Foo;
    
    fn add(self, foo: Foo) -> Self::Output {
        Foo {
            a: foo.a + self,
            b: foo.b + self
        }
    }
}

I want to implement a trait on this group of structs, taking advantage of this operation.我想利用这个操作在这组结构上实现一个特征。 That is, I want something like the following:也就是说,我想要以下内容:

trait Bar: Add<f64, Output = Self> + Sized {
    fn right_add(self, f: f64) -> Self {
        self + f
    }
    
    // Doesn't compile!
    fn left_add(self, f: f64) -> Self {
        f + self
    }
}

However, this currently doesn't compile, since the super-trait bound doesn't include the left addition of f64 to Self .但是,这目前无法编译,因为超级特征绑定不包括f64Self的左侧添加。 My question is: How can I state this commutative trait bound?我的问题是:我怎样才能 state 这个交换特征绑定?

( Playground link .) 游乐场链接。)

Edit: To be clear, I'm aware that right_add and left_add have the same output.编辑:要清楚,我知道right_addleft_add具有相同的 output。 I'm mainly interested in the ergonomics of not having to remember which is "correct" according to the compiler.我主要对根据编译器不必记住哪个是“正确”的人体工程学感兴趣。 In addition, I'm curious to learn how to do this, even if it's not strictly necessary.此外,我很想知道如何做到这一点,即使这不是绝对必要的。

Inverted trait bounds like this are the exact usecase for where syntax:像这样的倒置特征界限是where语法的确切用例:

trait Bar
where
    f64: Add<Self, Output = Self>,
    Self: Add<f64, Output = Self> + Sized,
{
    fn right_add(self, f: f64) -> Self {
        self + f
    }

    fn left_add(self, f: f64) -> Self {
        f + self
    }
}

Playground link 游乐场链接

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

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