You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust枚举匹配报错:non-exhaustive patterns: `Shot::Hit(_)`未覆盖

Rust枚举match非穷尽模式匹配错误分析与修复

原代码

enum Shot {
    Bullseye,
    Hit(f64),
    Miss
}

impl Shot {
    fn points(self) -> i32 {
        match self {
            Shot::Bullseye => 5,
            Shot::Hit(x) if x < 3.0 => 2, 
            Shot::Hit(x) if x >= 3.0 => 1, 
            Shot::Miss => 0
        }
    }
}

编译错误信息

error[E0004]: non-exhaustive patterns: `Shot::Hit(_)` not covered
  --> src/main.rs:23:15
   |
23 |         match self {
   |               ^^^^ pattern `Shot::Hit(_)` not covered
   |
note: `Shot` defined here
  --> src/main.rs:15:5
   |
13 | enum Shot {
   |      ----
14 |     Bullseye,
15 |     Hit(f64),
   |     ^^^ not covered

错误原因

Rust的match表达式要求必须穷尽枚举的所有变体,编译器不会分析分支中if条件的逻辑完备性。你这里虽然通过两个带条件的Shot::Hit(x)分支覆盖了所有可能的f64值,但编译器只会识别出这是两个带过滤条件的模式分支,认为存在未被匹配的Shot::Hit(_)情况,因此触发非穷尽模式的错误。

解决方法

有两种可行的修复方式:

方式一:合并Hit分支,内部做条件判断

将两个Hit分支合并,在分支代码块内处理数值判断,这样编译器能明确识别该分支覆盖了所有Shot::Hit变体:

enum Shot {
    Bullseye,
    Hit(f64),
    Miss
}

impl Shot {
    fn points(self) -> i32 {
        match self {
            Shot::Bullseye => 5,
            Shot::Hit(x) => if x < 3.0 { 2 } else { 1 },
            Shot::Miss => 0
        }
    }
}

方式二:添加兜底分支(不推荐)

保留原分支结构,添加一个逻辑上不会触发的Shot::Hit(_)兜底分支,满足编译器的穷尽性检查:

enum Shot {
    Bullseye,
    Hit(f64),
    Miss
}

impl Shot {
    fn points(self) -> i32 {
        match self {
            Shot::Bullseye => 5,
            Shot::Hit(x) if x < 3.0 => 2,
            Shot::Hit(x) if x >= 3.0 => 1,
            Shot::Hit(_) => unreachable!("所有Hit情况已被覆盖"),
            Shot::Miss => 0
        }
    }
}

这种方式虽然能通过编译,但冗余且不如第一种简洁,一般优先选择方式一。

内容的提问来源于stack exchange,提问作者pedro_bb7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:47:17