代码之家  ›  专栏  ›  技术社区  ›  Josif Hamed

铁锈火柴!宏的返回值不同,取决于值是否在变量中

  •  0
  • Josif Hamed  · 技术社区  · 1 年前

    我有一段代码:

    fn main() {
        let x = Some(1);
        let y = Some(2);
        println!("{}",matches!(x,y));
        println!("{}",matches!(x,Some(2)));
    }
    

    打印的 true false 我希望它两次返回false,因为的值 Some 不同。这种行为背后的原因是什么?y在引擎盖下面有阴影吗?

    1 回复  |  直到 1 年前
        1
  •  3
  •   kmdreko    1 年前

    这种行为背后的原因是什么?y在引擎盖下面有阴影吗?

    是的,这引入了一个新的绑定 y 这将匹配任何东西。此代码会产生警告,指示两者 y 使用了:

    warning: unused variable: `y`
     --> src/main.rs:3:9
      |
    3 |     let y = Some(2);
      |         ^ help: if this is intentional, prefix it with an underscore: `_y`
      |
      = note: `#[warn(unused_variables)]` on by default
    
    warning: unused variable: `y`
     --> src/main.rs:4:30
      |
    4 |     println!("{}",matches!(x,y));
      |                              ^ help: if this is intentional, prefix it with an underscore: `_y`
    

    这类似于 Why is this match pattern unreachable when using non-literal patterns? 但形式略有不同, matches!(x,y) 相当于此(请参见 source 对于 matches! ):

    match x {
        y => true,
        _ => false,
    }
    

    标识符用于在模式中创建新绑定(除非它们是常量),因此不使用具有该名称的变量。

    推荐文章