Skip to content

Use of clamp in generics does not compose with f32 and f64, maybe relax restriction to PartialOrd? #85508

Closed as not planned

Description

@stephanemagnenat

When using T::clamp() in generics, T must be Ord. Types f32 and f64 are not Ord but implements clamp since 1.50.0, yet they cannot be used in generics due to the Ord constraint.

A possible solution I can think of is relax the constraint for clamp() from Ord to PartialOrd.

I tried this code:

fn c<T: PartialOrd>(v: T, min: T, max: T) -> T {
    v.clamp(min, max)
}

fn main() {
    println!("{}", c(1.0, 0.0, 2.0));
}

I expected to see this happen: compilation success

Instead, this happened: error[E0599]: the method clamp exists for type parameter T, but its trait bounds were not satisfied

Meta

rustc --version --verbose:

rustc 1.52.1 (9bc8c42bb 2021-05-09)
binary: rustc
commit-hash: 9bc8c42bb2f19e745a63f3445f1ac248fb015e53
commit-date: 2021-05-09
host: x86_64-unknown-linux-gnu
release: 1.52.1
LLVM version: 12.0.0

Activity

  1. changed the title [-]Use of clamp in generics does not combine with f64, maybe relax restriction to PartialOrd?[/-] [+]Use of clamp in generics does not combine with f32 and f64, maybe relax restriction to PartialOrd?[/+] on May 20, 2021
  2. stephanemagnenat commented on May 20, 2021

    @stephanemagnenat
    Author

    This is of course not a compiler bug, but rather a typing limitation in std.

  3. changed the title [-]Use of clamp in generics does not combine with f32 and f64, maybe relax restriction to PartialOrd?[/-] [+]Use of clamp in generics does not compose with f32 and f64, maybe relax restriction to PartialOrd?[/+] on May 20, 2021
  4. stephanemagnenat commented on Aug 23, 2021

    @stephanemagnenat
    Author

    Similarly, it is not possible to generalize over float types when using min and max because they are not Ord.

    This is work-aroundable using the num-trait crate with functions clamp_min and clamp_max.

  5. Xaeroxe commented on Jan 1, 2022

    @Xaeroxe
    Contributor

    Yeah actually we talked about this when clamp was introduced. rust-lang/rfcs#1961 (comment)

    The conclusion we came to is that PartialOrd was too likely to lead to surprising behavior. Thanks to the num crate you can still write your software the way you want to though.

  6. Dylan-DPC commented on Apr 26, 2023

    @Dylan-DPC
    Member

    Closing this as it is intended by the RFC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions