Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

     > It's fine to punish people for coding in the wrong 
     way, but here I have to accomplish a task (sorting the
     array) and so the punishment serves no purpose at
     all except for making my experience worse.
Then Rust way is fine. It's merely 'punishing' you for not thinking things through at compile time (that floats are sortable), instead of at run time (dependent on input). Maybe you prefer to have fail dynamically, and that's fine, but that's preference, and the goals of Rust do not align with it.

If you find relying on it often, why not write a macro? So:

       xs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Less))
becomes:

      sort!(xs)
Also honestly, if this is a very common use case bring it up on Rust forums maybe people will add a macro. They added macro for generating N elements for a vector.


Why a macro? Why not just define that comparator as a function?

    fn value_nans_last<T: Float>(a: &T, b: &T) -> Ordering {
      match (a, b) {
        (x, y) if x.is_nan() && y.is_nan() => Ordering::Equal,
        (x, _) if x.is_nan() => Ordering::Greater,
        (_, y) if y.is_nan() => Ordering::Less,
        (_, _) => a.partial_cmp(b).unwrap()
      }
    }

    xs.sort_by(value_nans_last);


I haven't done sorting, so no knowledge of sort interface in Rust, but maybe so it works across different sortable collections?


There's no need to use a macro: you can abstract over different kinds of sortable collections using a trait. (That said, there's no real reason to generalize IMO: by far the most common case is sorting slices.)


> If you find relying on it often, why not write a macro?

Why not a function? I think people turn to macros in rust sometimes because of the necessity to think about the semantics of function calls. Should I use references or values? What are the trade-offs?

The amount of thinking you have to do to perform a good "extract method" refactoring is one of my least favorite things about the language, but falls out of some of my favorite things about it. All in all, I think it's worth the trade.

edit: Expanded a bit.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: