[英]Rust generic type implementation for right = |_a| |b| b
In TypeScript, I do:在打字稿中,我这样做:
const right = <T>(a: T) => <U>(b: U) => b;
const log = (msg: unknown) =>
right
(console.log(msg))
(msg);
log(1); // 1
log("hello"); // "hello"
log(right(1)(2)); // 2
Now, I want to implement the same code in Rust with generic types.现在,我想用泛型类型在 Rust 中实现相同的代码。
let right = |_a| |b| b;
let log = |msg| right(println!("{:?}", msg))(msg);
log(1); // 1
log("hello"); // compile error
log(right(1)(2)); // compile error
So far, the compile error is like this, and I know why and how the error occurs, and I know this is not a code using generic.到目前为止,编译错误是这样的,我知道错误发生的原因和方式,并且我知道这不是使用泛型的代码。
So my question is what would be a proper code to implement this in Rust using generic types to closure ?所以我的问题是什么是正确的代码拉斯特来实现这一点使用泛型类型关闭?
The problem here is that your closures are not generic.这里的问题是你的闭包不是通用的。 They are in fact fixed to a specific type and those types are inferred.它们实际上固定为特定类型,并且这些类型是推断出来的。 The compiler assigns them once with your first use, and then they don't match for subsequent uses.编译器在您第一次使用时分配它们一次,然后它们不匹配以供后续使用。
If you want to use generic types, it's going to be better to use an explicit function instead of a closure:如果要使用泛型类型,最好使用显式函数而不是闭包:
fn right<T, U>(_x: T) -> impl Fn(U) -> U {
|b| b
}
fn log<T: std::fmt::Debug>(msg: T) {
right(println!("{:?}", msg))(msg);
}
fn main() {
log(1); // 1
log("hello"); // hello
log(right(1)(2)); // 2
}
Those functions are explicitly generic and appropriately typed, so they'll be monomorphized as appropriate for each instantiation.这些函数是明确的通用和适当的类型,因此它们将根据每个实例化进行单态化。 If you're unhappy with the increased scope of those functions, you can push them into main
, and they'll be visible only from there, just like your closures.如果您对这些函数的范围增加不满意,您可以将它们推入main
,并且它们只能从那里可见,就像您的闭包一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.