将 Rust 泛型限制为自定义数据类型
Constraining Rust Generics to custom data types
考虑我构建的以下结构。这样做的目的
struct 是在 layers 变量中包含以下数据类型之一,或者是 2D Vector网络,或一维网格向量。我最初的计划是将 layers 变量设置为一个枚举(如下所示),但是我想在之后附加到枚举中的值它已设置 - 我没有
认为枚举允许不复制?
这让我想到了我的问题:如何将 layers 定义为
通用值并将其约束为仅允许 2D 向量
网络,还是网格的一维向量?即使与
枚举是可能的,我想使用泛型会更干净。
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>),
}
一段时间后,我设法找到了一个有效的解决方案。解决方案是定义一个“虚拟”特征,目前它什么都不做(但将来会)。后来我将该类型定义为实现虚拟特征的泛型。这是其中的一些代码:
下面的解决方案将通用类型“T”限制为节点或网格。
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 {
}
}
}
考虑我构建的以下结构。这样做的目的 struct 是在 layers 变量中包含以下数据类型之一,或者是 2D Vector网络,或一维网格向量。我最初的计划是将 layers 变量设置为一个枚举(如下所示),但是我想在之后附加到枚举中的值它已设置 - 我没有 认为枚举允许不复制?
这让我想到了我的问题:如何将 layers 定义为 通用值并将其约束为仅允许 2D 向量 网络,还是网格的一维向量?即使与 枚举是可能的,我想使用泛型会更干净。
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>),
}
一段时间后,我设法找到了一个有效的解决方案。解决方案是定义一个“虚拟”特征,目前它什么都不做(但将来会)。后来我将该类型定义为实现虚拟特征的泛型。这是其中的一些代码:
下面的解决方案将通用类型“T”限制为节点或网格。
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 {
}
}
}