Skirmantas Kligys
Skirmantas Kligys

Reputation: 826

Owned pointer to a trait

Why does the following fail and how can I store owned pointers to traits?

trait Trait {};
struct Struct;
impl Trait for Struct {};

struct Container {
  child: ~Trait
};
let container = ~Container { child: ~Struct };

error: mismatched types: expected ~main::test02::Trait but found ~main::test02::Struct (expected trait benchmark::test02::Trait but found ~-ptr)

Upvotes: 1

Views: 532

Answers (1)

Ramon Snir
Ramon Snir

Reputation: 7560

You have to cast the value:

trait Trait {}
struct Struct;
impl Trait for Struct {}

struct Container {
  child : ~Trait
}
fn main() {
    let container = ~Container { child: ~Struct as ~Trait };
    println("")
}

Upvotes: 4

Related Questions