generics - 一个函数如何要求一个类型实现一个特征而不删除现有的特征边界?

标签 generics struct rust traits type-parameter

我想要一个 main_func返回 T 类型的向量带有 SrObject 的结构性状

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`

我知道我没有 Default fn 中的特征 main_func<T: SrObject> , 但我怎样才能在不删除 SrObject 的情况下实现这一目标特质?

最佳答案

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

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

We can specify multiple trait bounds on a generic type by using +. If we needed to be able to use display formatting on the type T in a function as well as the summary method, we can use the trait bounds T: Summarizable + Display. This means T can be any type that implements both Summarizable and Display.

针对您的情况:

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将迭代器转换为集合,而不是手动推送元素。

另见:

关于generics - 一个函数如何要求一个类型实现一个特征而不删除现有的特征边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50180069/

相关文章:

c# - 我如何声明派生的 "shell"类,它们除了重命名外什么都不做?

c# - 为什么下面的代码不能编译?

c - 解释 `_Generic`错误消息: error: invalid type argument of unary '` *`' (have '` int`')

c++ - 尝试提取不是结构的值的组成部分。 C++

rust - 如何解决 "cannot index a value of type ` usize`"错误?

rust - 使用具有生命周期参数的关联类型特征的生命周期错误

methods - 有没有一种方法可以使用后缀表示法来调用 Rust 中的函数而不需要定义新的特征?

c# - 试图从 Mono.Cecil 引用 Task.ContinueWith<T>

unit-testing - 如何在 Rust 中测试结构的实例化?

json - 在 Go 中将大行扫描成结构