patternrustMajor
Can I use '<' and '>' in match?
Viewed 0 times
matchandusecan
Problem
I am trying to do a simple quadratic function that would return number of roots and their values via an enum:
This doesn't compile as it complains about ''. Is there a way to achieve this with
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 {
return QuadraticResult::None,
> 0 => return QuadraticResult::TwoRoots(0.0, 1.0),
_ => return QuadraticResult::OneRoot(0.0),
}
}This doesn't compile as it complains about ''. Is there a way to achieve this with
match or do I need to use ifSolution
You can use a match guard, but that feels more verbose than a plain
if statement:return match delta {
d if d QuadraticResult::None,
d if d > 0 => QuadraticResult::TwoRoots(0.0, 1.0),
_ => QuadraticResult::OneRoot(0.0),
}Code Snippets
return match delta {
d if d < 0 => QuadraticResult::None,
d if d > 0 => QuadraticResult::TwoRoots(0.0, 1.0),
_ => QuadraticResult::OneRoot(0.0),
}Context
Stack Overflow Q#47852269, score: 81
Revisions (0)
No revisions yet.