相关疑难解决方法(0)

有没有办法结合多个特征来定义新的特征?

有没有办法结合多个特征(通过继承?)来定义一个新的特征?我正在寻找像C++中的概念:

auto concept newConcept<typename T> : concept1<T>, concept2<T>, concept3<T> {};
Run Code Online (Sandbox Code Playgroud)

假设我想创建一个继承自的新特征Clone,Default以及其他一些特征,那可能吗?

rust

20
推荐指数
1
解决办法
6483
查看次数

提供方法cast和self to trait对象

我有一个特性,我想提供一种方法.该方法将根据一些帮助者来实现,这些帮助者没有业务在特征内,并且非常简单,动态多态性比使它们通用更有意义.所以我有代码

fn use_trait(x: &Trait) {
    println!("object says {}", x.needed());
}

trait Trait {
    fn needed(&self) -> &str;

    fn provided(&self) {
        use_trait(self);
    }
}

struct Struct();

impl Trait for Struct {
    fn needed(&self) -> &str {
        "Hello, world!"
    }
}

fn main() {
    Struct().provided();
}
Run Code Online (Sandbox Code Playgroud)

然而,哪个不能编译,错误:

error[E0277]: the trait bound `Self: std::marker::Sized` is not satisfied
 --> <anon>:9:19
  |
9 |         use_trait(self);
  |                   ^^^^ the trait `std::marker::Sized` is not implemented for `Self`
  |
  = help: consider adding a `where Self: …
Run Code Online (Sandbox Code Playgroud)

traits rust

6
推荐指数
1
解决办法
509
查看次数

标签 统计

rust ×2

traits ×1