函数参数的匿名结构类型

Roy*_*son 5 rust

在 Typescript 中,我可以这样做:

function foo(param: { a: string, b: number }) { }
Run Code Online (Sandbox Code Playgroud)

为了声明一个接受对象的函数,而不显式地将参数类型声明为命名类型,如下所示:

interface Parameter {
    a: string;
    b: number;
}

function foo(param: Parameter) {}
Run Code Online (Sandbox Code Playgroud)

有没有办法在 Rust 中做到这一点,或者我是否必须显式地将参数类型声明为命名类型?

小智 4

Rust 对元组、数组和结构体上的函数参数进行模式解构,如下所示:

fn f((a, b): (u32, i32), [x, y, z]: [String; 3]) { }
struct A { a: u32, b: String }
fn g(A { a, b }: A) { }
Run Code Online (Sandbox Code Playgroud)

但对于未命名类型/对象,它没有这样的语法,因为 Rust 中根本不存在对象。想象一下 Rust 有这样的语法:

fn f((a, b): (u32, i32), [x, y, z]: [String; 3]) { }
struct A { a: u32, b: String }
fn g(A { a, b }: A) { }
Run Code Online (Sandbox Code Playgroud)

有人会如何调用该函数?无法构造这种类型的实例。在 javascript (/typescript) 中这是可能的,因为动态类型,但在 Rust 中你必须知道一个类型才能构造它。

如果您对在函数中伪造关键字参数感兴趣,这可能会有所帮助:How to best *fake* keywords style function argument in Rust?

如果您想给元组命名并为其参数命名,则可以使用不稳定的bindings_after_at功能来启用此语法:

#![feature(bindings_after_at)]
fn f(my_tuple @ (a, b): (u32, u32)) {
    println!("this: {:?}", my_tuple);
    println!("is the same as: {:?}", (a, b));
}
// or this
fn g(arr @ [.., tail] : [u32; 5]) {
    println!("this: {}", arr[4]);
    println!("is the same as: {}", tail);
}
Run Code Online (Sandbox Code Playgroud)