RS.CLIPPY.MANUAL_CLAMP

Using a clamp pattern instead of the clamp function

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: manual_clamp. Copyright ©2025 The Rust Team. All rights reserved.

What it does

Identifies good opportunities for a clamp function from std or core, and suggests using it.

Why is this bad?

clamp is much shorter, easier to read, and doesn't use any control flow.

Limitations

This lint will only trigger if max and min are known at compile time, and max is greater than min.

Known issue(s)

If the clamped variable is NaN this suggestion will cause the code to propagate NaN rather than returning either max or min.

clamp functions will panic if max < min, max.is_nan(), or min.is_nan(). Some may consider panicking in these situations to be desirable, but it also may introduce panicking where there wasn't any before.

See also the discussion in the PR.

Examples

if input > max {
    max
} else if input < min {
    min
} else {
    input
}
input.max(min).min(max)
match input {
    x if x > max => max,
    x if x < min => min,
    x => x,
}
let mut x = input;
if x < min { x = min; }
if x > max { x = max; }

Use instead:

input.clamp(min, max)

Configuration

  • msrv: The minimum rust version that the project supports. Defaults to the rust-version field in Cargo.toml

    (default: current version)