I found this discussion about tuple splatting, but it is from 2014.
The example given is:
fn sum(x: i32, y: i32) -> i32 {
x + y
}
fn prepare_args () -> (i32, i32) {
(1, 2)
}
fn main() {
sum(prepare_args()); // Doesn't work
}
And the proposed solution is to roll your own apply
function:
fn apply<A,B,C>(f: |A,B|->C, t: (A,B)) -> C {
let (a,b) = t;
f(a,b)
}
fn main() {
apply(sum, prepare_args());
}
Is this currently the best way to go? If so, what is the correct syntax here? I get some errors including expected type, found
|at line 1 col 20
using the above.
Is there still no tuple splat operator?
A tuple is a collection of values of different types. Tuples are constructed using parentheses () , and each tuple itself is a value with type signature (T1, T2, ...) , where T1 , T2 are the types of its members. Functions can use tuples to return multiple values, as tuples can hold any number of values.
Tuple values are accessed with dot notation where we separate the tuple name and the value index number with a dot operator. Tuples cannot be iterated over like an array or collection. We can destruct a tuple by assigning its values into separate variables.
tuple is immutable because it's not allowed to change/reassign the pointer values saved in ob_item array.
I don't think there is a splat operator.
The code you found from 2014 is from before Rust 1.0, so it is outdated. To make the apply
function work in post 1.0 Rust, change it into the following:
fn sum(x: i32, y: i32) -> i32 {
x + y
}
fn prepare_args() -> (i32, i32) {
(1, 2)
}
fn apply<A, B, C, F>(f: F, t: (A, B)) -> C
where F : Fn(A, B) -> C
{
let (a, b) = t;
f(a, b)
}
fn main() {
let x = apply(sum, prepare_args());
println!("{}", x);
}
This code compiles and runs correctly on the Rust playground.
You could alternatively use f(t.0, t.1)
as the body of apply
, or destructure right there in the parameter list (Playground):
fn apply<A, B, C, F>(f: F, (a, b): (A, B)) -> C
where F : Fn(A, B) -> C
{
f(a, b)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With