[英]Can Rust cast between function types when I don't care about some of the arguments?
I have 3 function types:我有 3 function 类型:
type ThreadedFunction = fn(&mut Thread, Object) -> FunctionResult;
type UniversalFunction = fn(&mut Thread, Unused) -> FunctionResult;
type Function = fn(&mut Thread, &Method) -> FunctionResult;
static_assertions::assert_eq_size!(primitives::Unused, &Method);
static_assertions::assert_eq_size!(primitives::Unused, Object);
The universal functions ignore the second parameter, so I'd like to be able to use them in the two other contexts.通用函数忽略第二个参数,所以我希望能够在其他两个上下文中使用它们。 The sizes of Object
, Unused
and &Method
are the same. Object
、 Unused
和&Method
的大小相同。
I would like to be able to do something like:我希望能够做类似的事情:
pub fn unused(thread: &mut Thread, _: Unused) -> FunctionResult {
NormalReturn
}
pub fn somewhere() -> ThreadedFunction {
unused as ThreadedFunction
}
This is unsafe:这是不安全的:
error[E0605]: non-primitive cast: `for<'r> fn(&'r mut interpreter::Thread, interpreter::primitives::Unused) -> interpreter::FunctionResult {unused}` as `for<'r> fn(&'r mut interpreter::Thread, object::Object) -> interpreter::FunctionResult`
--> src/interpreter.rs:25:13
|
25 | unused as ThreadedFunction
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ invalid cast
Wrapping the cast in unsafe {}
doesn't help.用unsafe {}
包装演员表并没有帮助。
This could be impossible, but it would be very convenient to be able to do as it would save a bunch of code duplication.这可能是不可能的,但是能够这样做会非常方便,因为它可以节省大量代码重复。
No, you cannot perform this cast because the function references have different types.不,您不能执行此转换,因为 function 引用具有不同的类型。 All of the parameter types and return types must be the same for two functions to have the same type.所有参数类型和返回类型必须相同,两个函数才能具有相同的类型。
Instead, you can return a closure that doesn't capture any environment.相反,您可以返回一个不捕获任何环境的闭包。 Because of that, it can be automatically converted into a function:因此,它可以自动转换为 function:
fn somewhere() -> ThreadedFunction {
|a, b| unused(a, Unused)
}
That is equivalent to this wrapper function:这相当于这个包装器 function:
fn unused_adapted(thread: &mut Thread, _: Object) -> FunctionResult {
unused(thread, Unused)
}
fn somewhere() -> ThreadedFunction {
unused_adapted
}
See also:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.