Best Practice for Traits Being Used by Traits

⚓ Rust    📅 2025-09-30    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 31 days ago. The information described in this article may have changed.

I'm currently working on a small test library to showcase simple graph algorithms (e.g. DFS and BFS) for trees and what difference it makes in regards to performance and resource consumption to use lists, hash maps, etc. as data structures.

To make it a bit more approachable, I wanted to show that no matter the data, as long as certain set of data is available, the algorithms are quite generic. This generic approach is where my knowledge of Rust is quite a bit lacking.

For now, I have the following traits defined and I would like to make it better:

pub trait Node {
    /// Reference ID of the original node to allow for a mapping of the internal structure to the original one. Unique and also used as identifier for a node in this library.
    fn reference(&self) -> usize;

    /// The children of a node. Uses [reference] to correctly identify a node.
    fn children(&self) -> &Vec<usize>;
}

pub trait Tree {
    /// Setup  the internal data structure so that the algorithms can properly run
    fn init<N>(&mut self, root: usize, nodes: Vec<N>) -> Result<(), InvalidArgumentError>
    where
        N: Node;

    fn get_root(&self) -> Result<usize, GenericError>;

   ...
}

I would have then implemented using the following struct:

pub struct SimpleNode {
    ...
}

pub struct SimpleTree {
    root: usize,
    nodes: HashMap<usize, Box<dyn Node>>,
}

It feels like the wrong approach and I would highly appreciate pointers on how to make it better :slight_smile:

1 post - 1 participant

Read full topic

🏷️ Rust_feed