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.
}
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.
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.
let (a, b) = (10, Vec::new());
foo(a, b);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.