Rust 匹配意外结果

标签 rust rust-cargo

<分区>

为什么这段代码会给我奇怪的结果?

const VAR1: u16 = 1;
const VAR2: u16 = 2;
const VAR3: u16 = 3;
const VAR4: u16 = 4;

#[cfg(test)]
mod tests {
    // use {VAR1, VAR2, VAR3, VAR4};
    #[test]
    fn test_match() {
        let a = 4;
        match a {
            VAR1 => {
                println!("matched: 1");
            }
            VAR2 => {
                println!("matched: 2");
            }
            VAR3 => {
                println!("matched: 3");
            }
            VAR4 => {
                println!("matched: 4");
            }
            _ => {
                println!("not matched");
            }
        }
    }
}

//use {VAR1, VAR2, VAR3, VAR4}; 行被注释时,测试执行的结果是matched: 1。当use {VAR1, VAR2, VAR3, VAR4}; 没有注释时,结果是正确的,并且是匹配:4

为什么编译器在第一种情况下不会失败?

cargo 测试 -- --nocapture

rustc --version
rustc 1.16.0-nightly (7e38a89a7 2017-01-06)

您可以在这里找到测试项目代码https://github.com/asmsoft/rust-match-test

最佳答案

如果不使用VAR1VAR2VAR3VAR4,它们不在匹配范围,并且模式成为绑定(bind)。其余模式变得无法访问,您会收到以下警告:

  --> src/main.rs:28:13
   |
28 |             VAR4 => {
   |             ^^^^
   |
   = note: #[warn(unused_variables)] on by default

warning: unreachable pattern

如果您将打印品替换为:

match a {
    VAR1 => {
        println!("matched: 1 ({:?})", VAR1);
    }
}

因为 VAR1 现在有它匹配的值,它会打印

matched: 1 (4)

使用use,四个常量在范围内,您可以匹配它们。

关于Rust 匹配意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924718/

相关文章:

rust - 盒装特征创建背后的机制如何运作?

rust - Rust 项目中的工作区内依赖关系

rust - Rust-无法创建包

rust - 当我有最新的 rustc 和 cargo 版本时,为什么我会收到解析器功能的构建错误?

rust - 如何记录来自 Rust 编译器插件的宏?

rust - 遍历中RefCell的循环引用借用

rust - Cargo 安装的模块存储在 Rust 项目中的什么位置?

rust - 在 Rust 中计算两个 f64 向量的点积的最快方法是什么?

testing - 如何获取所有 cargo 测试的列表?

intellij-idea - Rust 编译模式之间的区别