rust 为什么不允许返回实现绑定特征的结构?[duplicate]

qltillow  于 2023-02-23  发布在  其他
关注(0)|答案(1)|浏览(112)
    • 此问题在此处已有答案**:

What makes impl Trait as an argument "universal" and as a return value "existential"?(1个答案)
replace impl trait return type with trait bound(1个答案)
12小时前关门了。
你能解释一下这个生 rust 的错误吗?

pub trait OrderEvent {}

#[derive(Debug)]
pub struct OrderCreatedEvent {
    pub order_id: String,
}

impl OrderEvent for OrderCreatedEvent {}

pub fn handle_create<E: OrderEvent>(_state: OrderState, command: CreateOrderCommand) -> Vec<E> {
    let events = vec![OrderCreatedEvent {
        order_id: command.order_id,
    }];

    events
}

拉斯特告诉我:

mismatched types [E0308] expected type parameter `E`,
found struct `OrderCreatedEvent` Note: expected struct `Vec<E>` found struct `Vec<OrderCreatedEvent>`

事件实现OrderEvent特征并且它是特征绑定的。为什么不允许这样做?

toiithl6

toiithl61#

请改用此签名:

pub fn handle_create(_state: OrderState, command: CreateOrderCommand) -> Vec<impl OrderEvent>

在Rust中,使用impl Trait作为类型在参数类型和返回类型中具有相反的含义。https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits

相关问题