gpt4 book ai didi

rust - 函数参数的匿名结构类型

转载 作者:行者123 更新时间:2023-12-03 11:25:28 46 4
gpt4 key购买 nike

在 typescript 中,我可以这样做:

function foo(param: { a: string, b: number }) { }
为了声明一个接受对象的函数,而不像这样显式地将参数类型声明为命名类型:
interface Parameter {
a: string;
b: number;
}

function foo(param: Parameter) {}
有没有办法在 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) { }
但是对于未命名的类型/对象,它没有这样的语法,因为对象在 rust 中根本不存在。
想象一下,rust 有这样的语法:
fn f(param: {a: String, b: String}) {} // Invalid code!
有人会如何调用该函数?没有办法构造这种类型的实例。在 javascript (/typescript) 中这是可能的,因为动态类型,但在 rust 中你必须知道一个类型才能构造它。
如果您对在函数中伪造关键字参数感兴趣,这可能会有所帮助: How to best *fake* keyword style function arguments 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);
}

关于rust - 函数参数的匿名结构类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65433592/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com