如何使用Rust中match语句拥有的值?

时间:2018-12-16 10:47:40

标签: 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]),
    }
}

1 个答案:

答案 0 :(得分:2)

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

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]),
    }
}