【问题标题】:How can I return a generic type from a member function in Rust如何从 Rust 中的成员函数返回泛型类型
【发布时间】:2019-11-17 18:51:26
【问题描述】:

我正在尝试用 Rust 编写一个通用矩阵类。我想要一个get 成员函数,它返回矩阵中给定索引处元素的副本。目前的代码如下所示:

mod math {
    pub struct Matrix<T> {
        rows: usize,
        columns: usize,
        data: Vec<T>,
    }

    impl<T> Matrix<T> where T: Copy {
        pub fn empty(rows: usize, columns: usize) -> Matrix<T> {
            return Matrix {
                rows: rows,
                columns: columns,
                data: Vec::with_capacity(rows * columns),
            };
        }

        pub fn get(&self, row: usize, column: usize) -> T {
            return self.data[column + row * self.columns];
        }
    }

    impl<T> PartialEq for Matrix<T>
    where
        T: PartialEq,
    {
        fn eq(&self, other: &Self) -> bool {
            if self.rows != other.rows || self.columns != other.columns {
                return true;
            }

            for i in 0..self.rows {
                for j in 0..self.columns {
                    if self.get(i, j) != other.get(i, j) {
                        return false;
                    }
                }
            }

            return true;
        }
    }
}

我从 Rust 编译器(版本 1.39.0)收到以下错误:

error[E0599]: no method named `get` found for type `&math::Matrix<T>` in the current scope
  --> <source>:33:29
   |
33 |                     if self.get(i, j) != other.get(i, j) {
   |                             ^^^ method not found in `&math::Matrix<T>`
   |
   = note: the method `get` exists but the following trait bounds were not satisfied:
           `T : std::marker::Copy`
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following traits define an item `get`, perhaps you need to implement one of them:
           candidate #1: `core::panic::BoxMeUp`
           candidate #2: `std::slice::SliceIndex`

我很难理解这个错误的含义。我需要使用一些额外的特征来约束T 类型吗?

【问题讨论】:

    标签: rust


    【解决方案1】:

    eq 中,selfMatrix&lt;T&gt; where T: PartialEq,因为这是定义eqimpl 的边界。调用get 需要它是Matrix&lt;T&gt; where T: Copy,因为这是定义getimpl 的边界。这就是错误消息的含义:

    方法get 存在,但不满足以下特征界限: T : std::marker::Copy

    绑定在一个 impl 上的类型不会自动传递给其他 impl。

    你可以解决这个问题

        impl<T> PartialEq for Matrix<T>
        where
            T: PartialEq + Copy
    

    或者,如果您不想这样做,您可以从 get 返回一个 &amp;T 并删除 where T: Copy

    【讨论】:

    • 谢谢!我不知道 impl 没有接受 Copy trait,但这是有道理的。
    • @JoshPeterson 它们故意不会自动继承,因此您可以为类型参数的特定子集定义方法(例如,仅Matrix&lt;u32&gt;
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 2019-11-08
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    相关资源
    最近更新 更多