Is it possible to unpack a tuple into function arguments?

无人久伴 提交于 2020-02-29 10:03:59

问题


If I want to unpack a tuple and pass it as arguments is there a way to do this:

//Does not compile
fn main() {
    let tuple = (10, Vec::new());
    foo(tuple);
}
fn foo(a: i32, b: Vec<i32>) {
    //Does stuff.
}

Instead of having to do this:

fn main() {
    let tuple = (10, Vec::new());
    foo(tuple.0, tuple.1);
}
fn foo(a: i32, b: Vec<i32>) {
    //Does stuff.
}

回答1:


On a nightly compiler:

#![feature(fn_traits)]

fn main() {
    let tuple = (10, Vec::new());
    std::ops::Fn::call(&foo, tuple);
}
fn foo(a: i32, b: Vec<i32>) {
}

There is AFAIK no stable way to do that.




回答2:


There is a way, using the magic of pattern matching:

fn main() {
    let tuple = (10, Vec::new());
    foo(tuple);
}

fn foo((a, b): (i32, Vec<i32>)) {
    // do stuff
}

As per Rust reference:

As with let bindings, function arguments are irrefutable patterns, so any pattern that is valid in a let binding is also valid as an argument.

So you can specify an argument like:

(a, b): (i32, Vec<i32>)

just like you would in a let statement.




回答3:


let (a, b) = (10, Vec::new());
foo(a, b);


来源:https://stackoverflow.com/questions/39878382/is-it-possible-to-unpack-a-tuple-into-function-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!