Home > Enterprise >  Constraining Rust Generics to custom data types
Constraining Rust Generics to custom data types

Time:10-05

Consider the following struct that I have built. The purpose of this struct is to contain one of the following data types in the layers variable, either a 2D Vector of Networks, or a 1D Vector of Meshes. My original plan was to set the layers variable to an Enum (shown below), however I would like to append to the value in the enum after it is set - which I don't think enum allows without copying?

Which brings me to my question: How can I define a layers as a generic value and constrain it to only allow a 2D Vector of Networks, or a 1D Vector of Meshes? Even if working with Enums is possible, I imagine using a generic would be much cleaner.

 pub(crate) struct Mapping {
     layers: NodeDefinition
 }
 
 impl Mapping {
     pub(crate) fn new(node_definition: NodeDefinition) -> Mapping {
         Mapping {
             layers: node_definition
         }
     }
 }
 
 pub(crate) enum NodeDefinition {
     NODE(Vec<Vec<Network>>),
     LEAF(Vec<Mesh>),
 }

CodePudding user response:

After some time I managed to get a solution working. The solution was define a "dummy" trait which, at the moment does nothing (but will in the future). I later defined the type to be a generic that implemented the dummy trait. Here is some of that code:

The solution below constrains the generic type "T" to either a Node or a Mesh.

pub(crate) struct Network<T> {
    guid: Uuid,
    input: bool,
    output: bool,
    subnet: T,
}

impl<T: Subnet> Network<T> {
    pub(crate) fn new(subnet: T) -> Network<T> {
        Network {
            guid: Uuid::new_v4(),
            input: true,
            output: true,
            subnet,
        }
    }
}

//// Concerned with Mesh Struct
pub(crate) struct Mesh {
}

impl Subnet for Mesh {}

impl Mesh {
    pub(crate) fn new() -> Mesh {
        Mesh {
        }
    }
}

/// Concerned with Node Struct
pub(crate) struct Node {
}

impl Subnet for Node {}

impl Node {
    pub(crate) fn new() -> Node {
        Node {
        }
    }
}
  • Related