【问题标题】:How can a function require that a type implement a trait without removing the existing trait bound?一个函数如何要求一个类型实现一个特征而不删除现有的特征绑定?
【发布时间】:2018-05-04 17:14:24
【问题描述】:

我正在尝试拥有一个 main_func,它返回一个具有 SrObject 特征的 T 结构类型的向量

struct TestA {
    value: u8,
}

pub trait SrObject {
    fn myfunc(&mut self);
}
impl SrObject for TestA {
    fn myfunc(&mut self) {
        unimplemented!();
    }
}
impl Default for TestA {
    fn default() -> TestA {
        TestA { value: 3u8 }
    }
}

fn main_func<T: SrObject>(t: T) -> Vec<T> {
    let mut v = Vec::<T>::new();
    for i in 0..10 {
        v.push(T::default());
        //v[i].myfunc();
    }
    return v;
}

它给出:

error[E0599]: no function or associated item named `default` found for type `T` in the current scope
  --> src/main.rs:22:16
   |
22 |         v.push(T::default());
   |                ^^^^^^^^^^ function or associated item not found in `T`
   |
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `default`, perhaps you need to implement it:
           candidate #1: `std::default::Default`

我知道我在 fn main_func&lt;T: SrObject&gt; 中没有 Default 特征,但是如何在不删除 SrObject 特征的情况下实现这一点?

【问题讨论】:

  • 您已经问了足够多的问题,您应该知道包含 整个 错误消息,而无需我为您编辑它。

标签: generics struct rust traits type-parameter


【解决方案1】:

我鼓励你回去重读The Rust Programming Language。这是 Rust 社区创建的免费在线书籍,涵盖了成为一名成功的 Rust 程序员所需了解的广泛知识。

在这种情况下,chapter on traits 提到了这个关于 trait bounds

我们可以使用+ 在泛型类型上指定多个特征边界。如果我们需要能够在函数中使用T 类型以及summary 方法的显示格式,我们可以使用特征边界T: Summarizable + Display。这意味着T 可以是同时实现SummarizableDisplay 的任何类型。

对于您的情况:

fn main_func<T: SrObject + Default>() -> Vec<T> {
    (0..10).map(|_| T::default()).collect()
}

或者

fn main_func<T>() -> Vec<T>
where
    T: SrObject + Default,
{
    (0..10).map(|_| T::default()).collect()
}

使其符合习惯的其他更改:

  • 调用Vec::new时不要指定v的类型;它会被推断出来。
  • 不要在函数末尾使用显式 return
  • 使用Iterator::mapIterator::collect 将迭代器转换为集合,而不是手动推送元素。

另见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2021-12-28
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多