Does Rust support using the infix operator as a function?

I am writing a function that produces piecewise multiplication of two arrays.

    xs.iter()
        .zip(ys).map(|(x, y)| x * y)
        .sum()

In some other languages ​​I can pass (*)as a function to map. Does Rust have this feature?

+4
source share
3 answers

Nnnyes. Varieties do not seem to be very.

You cannot write an operator as a name. But most operators are supported by traits, and you can write their name, so it is a * befficient Mul::mul(a, b), and you can pass Mul::mulfunctions as a pointer.

But this does not help in this case, because it Iterator::mapexpects FnMut((A, B)) -> C, and binary operators implement FnMut(A, B) -> C.

, . .

Iterator::map , arity ... , arity...

, .

+11

Rust infix, - , .

Rust : * , , std::ops::Mul.

, * , std::ops::Mul::mul:

xs.iter().zip(ys).map(Mul::mul).sum();

:

  • , , Mul ,
  • Mul::mul , xs.zip(ys) ( ).

, , "" ... , .

+7

No. The operator is *implemented in std::Ops::Mul, but it cannot be used directly:

use std::ops::Mul::mul;

fn main() {
    let v1 = vec![1, 2, 3];
    let v2 = vec![1, 2, 3];

    println!("{:?}", v1.iter().zip(v2).map(|(x, y)| mul).collect());
}

Will result in the following error:

error[E0253]: `mul` is not directly importable
 --> <anon>:1:5
  |
1 | use std::ops::Mul::mul;
  |     ^^^^^^^^^^^^^^^^^^ cannot be imported directly

You can enter your own function using the operator *, but there wouldn’t be much added value :).

+3
source

Source: https://habr.com/ru/post/1679138/


All Articles