Try to search your question here, if you can't find : Ask Any Question Now ?

Collection with Traits that return Self

HomeCategory: stackoverflowCollection with Traits that return Self
rupesh asked 2 weeks ago

I’m trying to have a collection of objects that implement a particular trait.

If I use a trait that returns a value, this works

use std::collections::BTreeMap;

struct World {
    entities: Vec<usize>,
    database: BTreeMap<usize, Box<ReadValue>>,
    //database : BTreeMap<usize,Box<ReadEcs>>, // Doesn't work
}

struct SourceInputGateway {
    entity_id: usize,
}

trait ReadValue {
    fn read(&self) -> f32;
}

impl ReadValue for SourceInputGateway {
    fn read(&self) -> f32 {
        0.0
    }
}

But if I want to return Self as a value then this doesn’t work, either as a method template param or associated type

trait ReadEcs {
    type T;
    fn read(&self) -> &Self::T;
}

impl ReadEcs for SourceInputGateway {
    type T = SourceInputGateway;
    fn read(&self) -> &Self::T {
        self
    }
}

What I would like to do is have a map of types that implement ReadEcs, the concrete type of which is not important.

1 Answers
Best Answer
Fernando answered 2 weeks ago
Your Answer

2 + 17 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com