-1

Here is a Godbolt link: https://godbolt.org/z/q9bsnMn7q

And here is what I am trying to solve:

use std::ops::{Add, Sub};

fn f(a: i32, b: i32, binop: &dyn Fn(i32, i32) -> i32) -> i32 {
    binop(a, b) as i32
}

fn main() {

    // Examples using Sub::sub and Add::add
    println!("{}", f(1, 2, &Add::add));
    println!("{}", f(1, 2, &Sub::sub));

    // This works (but seems non-idiomatic) compared to above
    let eq1 = |a, b| if a == b {1} else {0};
    let eq2 = |a, b| (a == b).into();

    println!("{}", f(1, 2, &eq1));
    println!("{}", f(1, 2, &eq2));

    // Is there something like this?
    // println!("{}", f(1, 2, &PartialEq::eq as i32));
}
arkethos
  • 31
  • 3
  • 1
    `a == b` returns `bool`, not `i32`, and `Eq::eq` does not exist (perhaps you meant `PartialEq::eq()`). – Chayim Friedman Oct 28 '22 at 13:10
  • Please provide a complete [mre] so that it is clear what you are trying to do. If it does not compile, include the full error message _verbatim_ from Cargo. – E_net4 Oct 28 '22 at 13:48
  • Unless there is something specific about this question, this is a duplicate of [How do you pass a Rust function as a parameter?](https://stackoverflow.com/questions/36390665/how-do-you-pass-a-rust-function-as-a-parameter). Please [edit] the question if the answers within do not answer what you are looking for. – E_net4 Oct 28 '22 at 13:50
  • 1
    Maybe you want to turn the return type of the closure into a generic type parameter, so you can pass in `PartialEq::eq`? If you still want to return `i32` from the wrapping function, you may need `T: Into` or similar. (It's hard to tell what problem you are trying to solve with the information given.) – Sven Marnach Oct 28 '22 at 15:02

1 Answers1

1

The equivalent to the operator functions in std::ops::{Add, Sub} for the == operator is std::cmp::PartialEq::eq().

You might be confused that the std::cmp::Eq trait does not have an eq() function as well, this is because it behaves more as a marker trait indicating that (for a particular type) the == operator is reflexive, symmetric, and transitive. Objects that implement the Eq trait still use std::cmp::PartialEq::eq() for the == operator.

effect
  • 1,279
  • 6
  • 13