在Java
中,我们可以将lambda表达式或方法引用作为只有一个方法的接口(interface)参数。而且这个特性可以大大简化代码。例如,
@FunctionalInterface
interface A {
void execute();
}
class B {
public void foo() {
System.out.println("foo in B");
}
public void bar() {
System.out.println("bar in B");
}
}
B b = new B();
然后,对于任何接受 A a
作为参数的方法,我们可以将 b::foo
或 b::bar
传递给它。
我的问题是:Rust 中函数接口(interface)和方法引用的等价性是什么? Rust 的 Trait 似乎没有提供这样的功能。
最佳答案
您通常会像这样实现它:
trait A {
fn execute(&self) -> ();
}
impl<T> A for T where T: Fn() -> () {
fn execute(&self) {
self()
}
}
impl
block 将实现任何 Fn() -> ()
的特征,它将与普通函数或 lambda 匹配。
fn foo() {
println!("foo")
}
fn use_a<T>(a: T) where T: A {
a.execute()
}
fn main() {
use_a(foo);
use_a(|| println!("bar"));
}
如果您想将其用作 B
的函数,您可能会将其作为 lambda 提供。
struct B {}
impl B {
fn foo(&self) {
println!("foo in B")
}
fn bar(&self) {
println!("bar in B")
}
}
fn use_a<T>(a: T) where T: A {
a.execute()
}
fn main() {
let b = B {};
use_a(|| b.foo());
use_a(|| b.bar());
}
您可以在 playground 上测试它.
关于java - Rust 在 Java 中函数式接口(interface)和方法引用的等价性是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68076503/