代码之家  ›  专栏  ›  技术社区  ›  garritfra

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

  •  1
  • garritfra  · 技术社区  · 6 年前

    我的目的是匹配文本文件中每一行的值。如果值与字符串匹配,则应将相应的操作码推送到矢量。否则,我想将值本身添加到向量中。无法使用值本身,因为它属于另一个作用域。

    如果我错了,是正确的,但我不能复制或克隆 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 回复  |  直到 6 年前
        1
  •  2
  •   Shepmaster Tim Diekmann    6 年前

    使用任意值而不是 _ . 现在的声明如下:

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