rust - 我如何使用 Rust 中的匹配语句拥有的值?

标签 rust ownership borrowing

我的意图是匹配文本文件中每一行的值。如果该值与字符串匹配,则应将相应的操作码推送到向量中。否则,我想将值本身添加到向量中。该值本身不能使用,因为它属于另一个范围。

如果我错了,请改正,但我无法复制或克隆 line 的值,因为它没有实现正确的特征。在 match 语句中借用值然后将其用作默认值 (_) 的最佳解决方案是什么,以防它不匹配任何字符串?

let buffered = BufReader::new(input);

for line in buffered.lines() {
    match line.unwrap().as_ref() {
        "nop" => instructions.push(0x00),
        "push" => instructions.push(0x01),
        "print" => instructions.push(0x02),
        "add" => instructions.push(0x03),
        "halt" => instructions.push(0xff),
        _ => instructions.push(line.unwrap().as_bytes()[0]),
    }
}

最佳答案

使用任意值代替 _。语句现在看起来像这样:

for line in buffered.lines() {
    match line.unwrap().as_ref() {
        "nop" => instructions.push(0x00),
        "push" => instructions.push(0x01),
        "print" => instructions.push(0x02),
        "add" => instructions.push(0x03),
        "halt" => instructions.push(0xff),
        x => instructions.push(x.as_bytes()[0]),
    }
}

关于rust - 我如何使用 Rust 中的匹配语句拥有的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801429/

相关文章:

rust - 如何为 clap_app! 的参数指定默认值宏观?

linux - mac OS X 和 linux 之间的 rsync 所有权

rust - 迭代递归结构时无法获取可变引用 : cannot borrow as mutable more than once at a time

rust - 如何使可变指针指向树节点的字段并对其进行变异?

rust - rust 双引用值

rust - 如何使用 Warp 检查授权 header ?

rust - 实例化 std::vec::IntoIter<i32> 时达到类型长度限制

pointers - 如何在不一直取消引用指针的情况下修复错误 "cannot move out of dereference"?

C++ 析构函数和所有权

rust - 函数,可变借用