簡體   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)

我是 rust 新手,我想用一個標量實現向量的頻繁數學乘法:k * v<\/strong> =(k * v0,k * v1,k* v2..)。 代碼如下:

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

簡而言之,沒有。

你遇到了“孤兒規則”。 基本思想是,如果要在 struct\/enum\/union Y<\/code>上實現 trait X<\/code> ,至少<\/em>必須在當前 crate 中定義其中之一。

這有時有些限制,但它是 Rust 的“連貫性規則”的產物。 一般來說,每個特征和類型的組合最多只能有 1 個實現。 所以下面的代碼是無效的:

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