Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple splat / apply in Rust

Tags:

tuples

rust

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?

like image 872
Imran Avatar asked Jun 01 '16 09:06

Imran


People also ask

What is tuples in Rust?

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.

How do you access tuple elements in Rust?

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.

Are tuples mutable in Rust?

tuple is immutable because it's not allowed to change/reassign the pointer values saved in ob_item array.


1 Answers

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)
}
like image 151
Magnus Hoff Avatar answered Oct 02 '22 02:10

Magnus Hoff