我可以使用'<'吗和'>'在比赛中? [英] Can I use '<' and '>' in match?

查看:81
本文介绍了我可以使用'<'吗和'>'在比赛中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个简单的二次函数,该函数将通过枚举返回根数及其值:

I am trying to do a simple quadratic function that would return number of roots and their values via an enum:

enum QuadraticResult {
    None,
    OneRoot(f32),
    TwoRoots(f32, f32),
}

fn solveQuadratic(a: f32, b: f32, c: f32) -> QuadraticResult {
    let delta = b * b - 4.0 * a * c;
    match delta {
        < 0 => return QuadraticResult::None,
        > 0 => return QuadraticResult::TwoRoots(0.0, 1.0),
        _ => return QuadraticResult::OneRoot(0.0),
    }
}

由于抱怨'<',因此无法编译.和'>'.有没有一种方法可以通过match来实现,或者我是否需要使用if

This doesn't compile as it complains about '<' and '>'. Is there a way to achieve this with match or do I need to use if

推荐答案

您可以使用匹配防护,但是比普通的if语句更冗长:

You can use a match guard, but that feels more verbose than a plain if statement:

return match delta {
    d if d < 0 => QuadraticResult::None,
    d if d > 0 => QuadraticResult::TwoRoots(0.0, 1.0),
    _   => QuadraticResult::OneRoot(0.0),
}

这篇关于我可以使用'&lt;'吗和'&gt;'在比赛中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆