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

Rust如何用match输出所有整除匹配结果 而非仅首个else if分支

实现方案

首先你的原始代码存在变量名不一致的问题:定义的变量是x,后续判断却用了未声明的number,需要先统一变量名。

要实现同时输出所有符合的整除条件,避免if-else if的短路逻辑,用match语法可以参考以下两种实现:


方案1:遍历检查(更易扩展)

把所有需要检查的除数和对应提示提前定义为列表,遍历过程中用match判断是否满足整除条件:

fn main() {
    let number = 6;
    // 待检查的除数与对应提示
    let check_items = [(4, "divisible by 4"), (3, "divisible by 3"), (2, "divisible by 2")];
    let mut has_matched = false;

    for (divisor, tip) in check_items {
        match number % divisor {
            0 => {
                println!("Number is {tip}");
                has_matched = true;
            }
            _ => {} // 不满足条件时无操作
        }
    }

    if !has_matched {
        // 修正原逻辑错误:所有整数都可被1整除,调整提示表述
        println!("Number not divisible by 4, 3, or 2");
    }
}

运行后输入6的输出为:

Number is divisible by 3
Number is divisible by 2

完全符合需求。


方案2:元组匹配(无需遍历)

如果不需要动态扩展检查项,也可以直接用match匹配所有判断结果的元组:

fn main() {
    let number = 6;
    match (number % 4 == 0, number % 3 == 0, number % 2 == 0) {
        (d4, d3, d2) => {
            if d4 { println!("Number is divisible by 4"); }
            if d3 { println!("Number is divisible by 3"); }
            if d2 { println!("Number is divisible by 2"); }
            if !(d4 || d3 || d2) {
                println!("Number not divisible by 4, 3, or 2");
            }
        }
    }
}

运行效果和方案1完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:15:09