类型擦除用于锈蚀中的功能



考虑一下这个C++代码:

#include <iostream>
#include <functional>
using namespace std;
std::function<int(int, int)> foo(int c) {
auto add = [] (int a, int b) { return a + b; };
auto sub = [] (int a, int b) { return a - b; };
if (c > 42) {
return add;
} else {
return sub;
}
}
int main() {
cout << foo(100)(10, 20) << 'n';
}

两个lambda(addsub(都通过std::function进行类型擦除,然后在main中调用该函数。我想知道如何在铁锈中复制这种图案?

您的示例的一个相当精确的翻译是以下片段。

fn foo(c: i32) -> Box<dyn Fn(i32, i32) -> i32> {
let add = |a, b| a + b;
let sub = |a, b| a - b;
Box::new(if c > 42 { add } else { sub })
}
fn main() {
println!("{}", foo(100)(10, 20));
}

一种类型的闭包是不可命名的,所以我们将其强制为一个trait对象并将其存储在堆上,据我所知,这与std::function所做的大致相同。

最新更新