使用枚举对结构进行分组

2024-04-12

在 Rust 中,应该如何对相关结构进行分组,以便函数签名可以接受多种不同类型,同时引用方法体内的具体类型?

为了简单起见,设计了以下示例:

enum Command {
    Increment {quantity: u32},
    Decrement {quantity: u32},
}

fn process_command(command: Command) {
    match command {
        Command::Increment => increase(command),
        Command::Decrement => decrease(command),
    };
}

fn increase(increment: Command::Increment) {
    println!("Increasing by: {}.", increment.quantity);
}

fn decrease(decrement: Command::Decrement) {
    println!("Decreasing by: {}.", decrement.quantity);
}

fn main() {
    let input = "Add";
    let quantity = 4;

    let command: Command = match input {
        "Add" => Command::Increment { quantity: quantity },
        "Subtract" => Command::Decrement { quantity: quantity },
        _ => unreachable!(),
    };

    process_command(command);
}

编译结果出现以下两个错误:

src/main.rs:13:24: 13:42 error: found value name used as a type: DefVariant(DefId { krate: 0, node: 4 }, DefId { krate: 0, node: 5 }, true) [E0248]
src/main.rs:13 fn increase(increment: Command::Increment) {
                                      ^~~~~~~~~~~~~~~~~~
src/main.rs:17:24: 17:42 error: found value name used as a type: DefVariant(DefId { krate: 0, node: 4 }, DefId { krate: 0, node: 8 }, true) [E0248]
src/main.rs:17 fn decrease(decrement: Command::Decrement) {
                                      ^~~~~~~~~~~~~~~~~~
error: aborting due to 2 previous errors

如果我单独声明结构,并将结构包装在枚举中的元组结构(正确的术语?)中,那么我会得到预期的结果,但是由于冗长和类似的类型名称遍布各处,我怀疑我误解了某事:

struct Increment {
    quantity: u32,
}

struct Decrement {
    quantity: u32,
}

enum Command {
    Increment(Increment),
    Decrement(Decrement),
}

fn process_command(command: Command) {
    match command {
        Command::Increment(increment) => increase(increment),
        Command::Decrement(decrement) => decrease(decrement),
    };
}

fn increase(increment: Increment) {
    println!("Increasing by: {}.", increment.quantity);
}

fn decrease(decrement: Decrement) {
    println!("Decreasing by: {}.", decrement.quantity);
}

fn main() {
    let input = "Add";
    let quantity = 4;

    let command: Command = match input {
        "Add" => Command::Increment(Increment { quantity: quantity }),
        "Subtract" => Command::Decrement(Decrement { quantity: quantity }),
        _ => unreachable!(),
    };

    process_command(command);
}

运行输出:

Increasing by: 4.

将结构包装在共享相同名称的枚举类型(术语?)中真的是最好的解决方案吗?Command::Increment(Increment { quantity: 7 })


是的,这是您沿着这条实施路线所能得到的最好的结果。枚举只是一种类型;它的变体纯粹是变体,而不是类型。

另一种选择是使用特征和泛型:

struct Increment {
    quantity: u32,
}

struct Decrement {
    quantity: u32,
}

trait Command {
    fn process(self);
}

impl Command for Increment {
    fn process(self) {
        println!("Increasing by {}", self.quantity);
    }
}

impl Command for Decrement {
    fn process(self) {
        println!("Decreasing by {}", self.quantity);
    }
}

当然,这并不是直接的类比。如果你想存储一个command您需要更改的可能不同的类型process采取self: Box<Self> or &self,并且您需要使用Box<Command> or &Command,但这是另一种可能适合您要求的做事方式。就定义而言,它更纯粹。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用枚举对结构进行分组 的相关文章

随机推荐

  • SQL 错误:ORA-00913:值太多

    两个表在表名 列名 数据类型和大小方面相同 这些表位于不同的数据库中 但我习惯于 当前登录 hr 用户 insert into abc employees select from employees where employee id 10
  • Stripe 结账模式的事件或方法

    有什么方法可以在 Stripe Checkout 模式关闭时触发事件吗 Stripe 的模式关闭和响应传递之间存在大约 0 5 1 秒的延迟 那时 用户可能会点击离开页面等 为了解决这个问题 我们可以执行一些操作 例如禁用所有链接或在页面上
  • 如何在现有 Windows 应用程序中获得 ATL 支持

    我正在 Visual Studio 2012 中使用 Qt 5 3 1 构建一个应用程序 我还想使用一个硬件库 这需要我向项目添加一个简单的 ATL 对象 这可以通过使用 Visual Studio 向导来完成 该向导抱怨我的项目既不是 M
  • 如何确定函数特化的主要模板?

    函数模板专业化的主要模板通常是非常直观的 但是 我正在寻找正式的规则来理解更令人惊讶的情况 例如 template
  • com.google.gwt.user.client.rpc.InknownRemoteServiceException

    我的 GWT 应用程序有问题 我部署在 Jetty 服务器上并运行 但是当我执行服务器调用 GWT 服务器包上的类 时 服务器返回错误消息 消息是 7 0 6 http localhost zbapp zb app A31E1254E17F
  • 抑制 make clean 中的消息(Makefile 无提示删除)

    我想知道如何避免 Makefile 中出现一些回声 clean rm fr o 该规则将打印 gt make clean rm fr o gt 我怎样才能避免这种情况 首先 实际的命令必须位于下一行 或者至少 GNU Make 是这样 它可
  • 在所有存储过程中搜索模式然后打开它进行更改的方法

    如何在所有存储过程中搜索某个模式 然后打开要编辑的存储过程 SQL Server 2005 内部有内置的东西吗 或者是否有任何第三方插件可以进行此搜索 我也在使用 Red Gate 的 SQL Prompt 但我没有注意到该选项 目前我正在
  • Zend_Db:如何从表中获取行数?

    我想知道一个表中有多少行 我使用的数据库是MySQL数据库 我已经有一个 Db Table 类 用于像这样的调用fetchAll 但我不需要表中的任何信息 只需要行数 如何在不调用的情况下获得表中所有行的计数fetchAll count d
  • 重写大型 IN 子句的最高效方法是什么?

    我使用 go 和 gorm 编写了一个 API 它在我们的数据库上运行计算并返回结果 我刚刚达到了参数限制IN使用聚合时的条件 查询示例 SELECT SUM total amount from Table where user id in
  • 使用 While() 结构时 Gridview 不会填充。 C# ASP.Net

    我在使用此网格视图时遇到问题 我正在用查询填充它 但是 如果我使用 while reader Read 结构 它就不会填充甚至不会出现 没有 while 结构 它工作得很好 但是 我需要访问两个特定字段 代码如下 SqlDataReader
  • getLastknownLocation() 在 nexus 上返回 null 值

    我正在开发基于位置的项目 我使用以下代码 我正在为该项目使用 google api 8 lm requestLocationUpdates LocationManager GPS PROVIDER 0 0 this currloc lm g
  • 为什么我们应该总是从函数返回值?

    我不是一个编程高手 但多次听程序员说我们应该始终从函数返回值 我想知道原因 函数不需要返回任何内容 如果您查看 C 函数 您会发现其中许多函数不需要返回任何内容 好吧 不是明确地 void nonReturningFunction cons
  • Python:有限制的非线性优化(Gekko?)

    我希望能够用Python解决以下问题 给定观测数据 x 1 x n 和已知的固定目标 B 和公差 E 求解参数 a0 a1 和 a2 从而最小化 总和 w i 2 其中 w i exp a0 a1x i a2x i 2 具有以下两个限制 s
  • 拆分包含两者的字符串中的数字和字母

    我正在尝试分割以下 或类似 字符串 08 27 2015 07 25 00AM 目前我使用 var parts date split 0 9a zA Z g 这导致 02 27 2012 03 25 00AM 问题在于00AM部分 我也想分
  • 在 Visual Studio 中的项目之间共享预编译头

    我有一个包含许多 Visual C 项目的解决方案 所有项目都使用 PCH 但有些项目打开了特定的编译器开关以满足项目特定的需求 这些项目中的大多数在各自的 stdafx h 中共享相同的标头集 STL boost 等 我想知道是否可以在项
  • 网页抓取、屏幕抓取、数据挖掘技巧? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 在 Python (2.7) 中比较两个相同的对象返回 False

    我在Python中有一个函数叫做object from DB 该定义并不重要 只是它采用 ID 值作为参数 使用sqlite3库从 db 文件中的表中提取匹配值 然后在对象初始化时使用这些值作为参数 使用此函数不会改变数据库 鉴于此 这个示
  • 有向加权图的邻接表

    我使用邻接表来表示有向加权图 并基于以下提供的示例代码this https stackoverflow com questions 58306 graph algorithm to find all connections between
  • 使用 ggplot2 绘制“序列徽标”?

    是否 合理 可能绘制一个序列标志图 http en wikipedia org wiki Sequence logo使用ggplot2 有一个基于 网格 的包可以做到这一点 称为 seqLogo http www bioconductor
  • 使用枚举对结构进行分组

    在 Rust 中 应该如何对相关结构进行分组 以便函数签名可以接受多种不同类型 同时引用方法体内的具体类型 为了简单起见 设计了以下示例 enum Command Increment quantity u32 Decrement quant