The trait cannot be made into an object

Viewed 36886

I have the following code:

extern crate futures; // 0.1.24

use futures::Future;
use std::io;

struct Context;

pub trait MyTrait {
    fn receive(context: Context) -> Future<Item = (), Error = io::Error>;
}

pub struct MyStruct {
    my_trait: MyTrait,
}

When I try to compile it I get the error message:

error[E0038]: the trait `MyTrait` cannot be made into an object
  --> src/lib.rs:13:5
   |
13 |     my_trait: MyTrait,
   |     ^^^^^^^^^^^^^^^^^ the trait `MyTrait` cannot be made into an object
   |
   = note: method `receive` has no receiver

I think I know why it happens, but how do I refer to the trait from the struct? Is it possible? Maybe there are other ways to implement the same behavior?

3 Answers

There is a fourth option available, but this will make your struct unsized, a.k.a. you will not be able to create instances of this struct.

pub trait MyTrait {}

pub struct MyStruct {
    my_trait: dyn MyTrait + 'static,
}

This means that MyStruct is an unsized type, and you cannot create direct instances of such type. As Rust currently does not have a way to allocate structs directly on the stack, I do not know if you can create an instance of such a type at all. But hey, it compiles.

Related