简体   繁体   English

"<i>Is possible to implement traits on generic types?<\/i>可以在泛型类型上实现特征吗?<\/b> <i>(Rust)<\/i> (锈)<\/b>"

[英]Is possible to implement traits on generic types? (Rust)

I'm new to rust, and I want to implement the frequent math multiplication of a vector by a scalar: k * v<\/strong> =(k * v0,k * v1,k* v2..).我是 rust 新手,我想用一个标量实现向量的频繁数学乘法:k * v<\/strong> =(k * v0,k * v1,k* v2..)。 The code is the following:代码如下:

#[derive(Debug)]
struct V(Vec<i32>);

impl std::ops::Mul<V> for i32 {
    type Output = V;
    fn mul(self, v: V) -> V {
        V(v.0.iter().map(|v| v * self).collect())
    }
}

fn main() {
    let v = V(vec![1,2]);
    println!("{:?}", 3 * v);
}

In short, no.简而言之,没有。

You're running into the "orphan rule".你遇到了“孤儿规则”。 The basic idea is that if you want to implement a trait X<\/code> , on a struct\/enum\/union Y<\/code> , at least one<\/em> of those must be defined in the current crate.基本思想是,如果要在 struct\/enum\/union Y<\/code>上实现 trait X<\/code> ,至少<\/em>必须在当前 crate 中定义其中之一。

This is somewhat restrictive at times, but it is a product of Rusts "coherence rules".这有时有些限制,但它是 Rust 的“连贯性规则”的产物。 In general, every combination of traits and types must have at most 1 implementation.一般来说,每个特征和类型的组合最多只能有 1 个实现。 So the following code is not valid:所以下面的代码是无效的:

struct Wrapper<T>(T);

trait Print {
  fn print(&self);
}

impl Print for Wrapper<i32> {
  fn print(&self) {
    println!("a very special int: {}", self);
  }
}

impl<T: Display> Print for Wrapper<T> {
  fn print(&self) {
    print!("a normal type: {}", self);
  }
}

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

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