如何声明符合函数类型的常规(非关闭)函数? [英] How do I declare a regular (non-closure) function that adheres to a function type?
问题描述
我有一个具有共同签名的不同排序函数的集合,因此它们可以互换地传递给其他函数.我希望能够内联声明每个都应匹配相同的签名,因此如果其中之一与之中断,我将在上下文中得到警告.
I have a collection of different sort functions with a common signature so they can be passed interchangeably to other functions. I want to be able to declare inline that each should match the same signature, so I'll be warned contextually if one of them breaks with it.
Rust具有用于声明函数类型的语法:
Rust has a syntax for declaring function types:
type Foo = Fn(i32) -> i32;
fn bar(func: &Foo) {
func(12);
}
我不知道如何声明一个遵循函数类型的常规(非关闭)函数:
What I can't figure out is how to declare a regular (non-closure) function that adheres to a function type:
// this works and can be passed as a Foo, but
// duplicates code and isn't checked against Foo
fn blah(x: i32) -> i32 {
return x * 2;
}
// this isn't valid syntax
fn blah(x): Foo {
return x * 2;
}
这是其他一些具有函数类型的语言的常见做法.是否有我不知道的语法,这是一项即将推出的功能,还是出于某种技术原因阻止将其添加到Rust?
This is common practice in some other languages that have function types. Is there a syntax I don't know about, is this an upcoming feature, or is there some technical reason preventing it from being added to Rust?
注意;像这样的东西也可以达到我的目的,即使它会比较笨拙:
Note; something like this would also serve my purpose, even though it'd be more clunky:
fn blah(x: i32) -> i32 {
return x * 2;
}: Foo
推荐答案
Rust具有用于声明函数类型的语法:
Rust has a syntax for declaring function types:
type Foo = Fn(i32) -> i32;
这不是 这样的语法(您可能会因为它没有按照您的要求进行操作而推断出这一点).这将创建类型为dyn Fn(i32) -> i32
的类型别名.
This is not such a syntax (as you might infer by the fact that it doesn't do what you want). This creates a type alias of the type dyn Fn(i32) -> i32
.
您可以通过使用函数指针并创建一个未使用的变量集来实现所需的功能:
You can achieve some of what you want by using a function pointer and creating an unused variable set to the function:
type MyType = fn(i32) -> i32;
fn blah(x: i32) -> i32 {
x * 2
}
const _IGNORE: MyType = blah;
但是,我同意您以非惯用的Rust方式进行此操作的评论.您想要创建一个事物遵循的界面,而在Rust中,这是一个 特征 :
However, I agree with the comments that you are going about this in a non-idiomatic Rust manner. You want to create an interface that things adhere to, and in Rust that's a trait:
trait Sort {
fn foo(_: i32) -> i32;
}
struct A;
impl Sort for A {
fn foo(x: i32) -> i32 {
x * 2
}
}
当您意指fn(String)
时,通过提供fn(String)
可以防止意外地越过溪流";前者是打印此字符串",后者是删除命名的文件".函数签名充其量是一个弱接口.
This prevents accidentally "crossing the streams" by providing a fn(String)
when you meant an fn(String)
; the former being "print this string" and the latter being "delete the file named". Function signatures are, at best, a weak interface.
另请参阅:
- What does "dyn" mean in a type?
- How to enforce that a type implements a trait at compile time?
这篇关于如何声明符合函数类型的常规(非关闭)函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!