元组splat /适用于Rust

Imr*_*ran 5 tuples rust

我发现这个关于元组splatting的讨论,但它是从2014年开始的.

给出的例子是:

fn sum(x: i32, y: i32) -> i32 {
    x + y
}

fn prepare_args () -> (i32, i32) {
    (1, 2)
}

fn main() {
    sum(prepare_args()); // Doesn't work
}
Run Code Online (Sandbox Code Playgroud)

建议的解决方案是推出自己的apply功能:

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());
}
Run Code Online (Sandbox Code Playgroud)

这是目前最好的方式吗?如果是这样,这里的语法是什么?我得到一些错误,包括expected type, found| at line 1 col 20使用上面的.

还有没有元组splat运算符吗?

Mag*_*off 6

我不认为有一个splat运算符.

您在2014年找到的代码来自Rust 1.0之前的代码,因此它已经过时了.要使该apply功能在1.0之后的Rust中运行,请将其更改为以下内容:

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);
}
Run Code Online (Sandbox Code Playgroud)

此代码在Rust操场上正确编译和运行.

您也可以在参数列表(Playground)中将其f(t.0, t.1)用作身体apply或体系结构:

fn apply<A, B, C, F>(f: F, (a, b): (A, B)) -> C
    where F : Fn(A, B) -> C
{
    f(a, b)
}
Run Code Online (Sandbox Code Playgroud)


Mat*_* M. 5

证明消极是非常困难的......

据我所知,确实没有元组splat运算符.但是,Fn*特征族(Fn)只需要一个参数作为元组.

在夜间编译器上,激活一些不稳定的功能,您可以使用:

#![feature(fn_traits)]
#![feature(unboxed_closures)]

fn sum(x: i32, y: i32) -> i32 {
    x + y
}

fn prepare_args () -> (i32, i32) {
    (1, 2)
}

fn main() {
    let func: &Fn(i32, i32) -> i32 = &sum;
    let result = func.call(prepare_args());
    println!("{:?}", result);
}
Run Code Online (Sandbox Code Playgroud)

不太理想,但是在没有对可变参数的支持的情况下,你总是需要知道元组元素的数量,所以值很低.