2

I'm trying to create a struct with a container that supports instance creation with default. Here's a minimal example:

#[derive(Default)]
struct Container<T> {
    values: Vec<T>,
}

impl<T> Container<T> {
    fn new() -> Self {
        Default::default()
    }
}

fn main() {}

Why does this code fail to compile with

error[E0277]: the trait bound `T: std::default::Default` is not satisfied
 --> src/main.rs:8:9
  |
8 |         Default::default()
  |         ^^^^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `T`
  |
  = help: consider adding a `where T: std::default::Default` bound
  = note: required because of the requirements on the impl of `std::default::Default` for `Container<T>`
  = note: required by `std::default::Default::default`

I could understand if I used something like Vec::resize_default() but for what is it needed here?

user2011659
  • 847
  • 1
  • 7
  • 15
  • Implementing Default for Container indeed does compile. – user2011659 May 27 '18 at 18:38
  • Yeah this is one of those unpleasant corner cases. It would be better if `#[derive]` were not defined like this, but it's what we have right now – trent May 27 '18 at 18:41
  • I don't get your problem. Have you read the help? `help: consider adding a 'where T: std::default::Default' bound` that's all you need. – hellow May 28 '18 at 05:54
  • Have you read the question? In this case the compiler wants T to implement Default even though its not needed. – user2011659 May 28 '18 at 18:48

0 Answers0