具有大小的超级特征的特征仍然有错误“std :: marker :: Sized不满意”[重复]

问题描述 投票:3回答:1

这个问题在这里已有答案:

我有以下代码:

use std::collections::HashMap;

trait T: Sized {}

struct A;

impl T for A {}

fn main() {
    let h: HashMap<String, T>;
}

但编译器抱怨:

error[E0277]: the trait bound `T: std::marker::Sized` is not satisfied
  --> src\main.rs:10:12
   |
10 |     let h: HashMap<String, T>;
   |            ^^^^^^^^^^^^^^^^^^ `T` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `T`
   = note: required by `std::collections::HashMap`

error[E0038]: the trait `T` cannot be made into an object
  --> src\main.rs:10:12
   |
10 |     let h: HashMap<String, T>;
   |            ^^^^^^^^^^^^^^^^^^ the trait `T` cannot be made into an object
   |
   = note: the trait cannot require that `Self : Sized`

我不明白错误信息,因为我把我的特质T标记为Sized。我错过了什么吗?

rust traits
1个回答
5
投票

因为我把我的特质T标记为Sized

不,你没有。你已经说过任何实现T的类型都必须是Sized。特质本身仍未实现。你需要一个特质对象(例如Box<T>)或某种泛型(在这种情况下你不能做)。

© www.soinside.com 2019 - 2024. All rights reserved.