3

I have the following code:

use std::collections::HashMap;

trait T: Sized {}

struct A;

impl T for A {}

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

But the compiler complains:

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`

I don't understand the error messages, because I've marked my trait T as Sized. Am I missing something?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Count Zero
  • 495
  • 6
  • 15

1 Answers1

5

because I've marked my trait T as Sized

No, you haven't. You've said that any type that implements T must be Sized. The trait itself is still unsized. You either need a trait object (e.g. Box<T>) or some kind of generic (which you cannot do in this context).

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366