1

Unpacking a tuple as arguments and calling a function with those values is covered by Is it possible to unpack a tuple into function arguments?, but is it possible to do the same trick on methods?

#![feature(fn_traits)]

struct Foo;

impl Foo {
    fn method(&self, a: i32, b: i32) {
        println!("{:?}, {:?}", a, b);
    }
}

fn main() {
    let foo = Foo;
    let tuple = (10, 42);

    // does not compile
    //foo.method.call(tuple);

    // nor this one
    //std::ops::Fn::call(&foo.method, tuple);
}

For both I get the following error:

error[E0615]: attempted to take value of method `method` on type `Foo`
  --> src/main.rs:20:9
   |
20 |     foo.method.call(tuple);
   |         ^^^^^^ help: use parentheses to call the method: `method(...)`

I do not control the method I call, so changing the signature to accept tuples is not an option.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

5

Methods are functions that

  1. Are associated with a type (called associated functions). Most people are familiar with "constructor" associated functions like new. These are referenced as Type::function_name.
  2. Take some kind of Self as the first argument.

Thus you need to use Foo::method and provide a matching self:

#![feature(fn_traits)]

struct Foo;

impl Foo {
    fn method(&self, a: i32, b: i32) {
        println!("{:?}, {:?}", a, b);
    }
}

fn main() {
    let foo = Foo;
    let tuple = (&foo, 10, 42);
    std::ops::Fn::call(&Foo::method, tuple);
}

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Even though I know about the universal function call syntax, I always assumed that the &self is some kind of magic, not just sugar. Wow, thank you! – Hollay-Horváth Zsombor Feb 24 '20 at 21:33
  • 2
    @Hollay-HorváthZsombor it’s properly called [*fully qualified syntax*](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name), and yeah, `self` in method arguments is [just syntax sugar](https://stackoverflow.com/q/25462935/155423). – Shepmaster Feb 24 '20 at 22:05