在Typescript中,我可以这样做:
function foo(param: { a: string, b: number }) { }
为了声明一个接收对象的函数,而不显式地将参数类型声明为命名类型,可以这样写:
interface Parameter {
a: string;
b: number;
}
function foo(param: Parameter) {}
有没有一种方法可以在 Rust 中实现这个,或者我必须显式地将参数类型声明为命名类型?
在Typescript中,我可以这样做:
function foo(param: { a: string, b: number }) { }
为了声明一个接收对象的函数,而不显式地将参数类型声明为命名类型,可以这样写:
interface Parameter {
a: string;
b: number;
}
function foo(param: Parameter) {}
fn f((a, b): (u32, i32), [x, y, z]: [String; 3]) { }
struct A { a: u32, b: String }
fn g(A { a, b }: A) { }
但是在Rust中没有未命名类型/对象的语法,因为对象在Rust中根本不存在。
想象一下如果Rust有这样的语法:
fn f(param: {a: String, b: String}) {} // Invalid code!
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);
}
您可以使用元组:
fn foo(param: (String, usize)) {
let a: String = param.0;
let b: usize = param.1;
}
fn foo((a, b): (String, usize)) {
// you can now access `a` and `b` here
}
struct Employee(String);
struct Customer(String);
fn handle_order(employee: Employee, customer: Customer){}
handle_order(customer, employee)
,在具有结构类型的语言中不会被注意到,但在名义类型中会触发编译错误。Employee
添加字段。在这种情况下,可以确保在修复 Employee 的所有用途后完成重构。在具有结构类型的程序中,无法确定是否完成了重构,因为可能存在发送 Customer 而不是 Employee 的代码,因此结构类型程序的重构要困难一些。