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
Avatarrupesh asked 5 months 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 {

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 {

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
AvatarFernando answered 5 months ago
Your Answer

9 + 16 =

Popular Tags

WP Facebook Auto Publish Powered By :