function - 从存储在结构中引用的函数不会放弃所有权
问题描述
我正在编写一个算法测试平台来比较 Rust 的性能。
我想在结构中存储一堆算法的函数,并将这些函数应用于一些数据。当我通过引用调用存储在结构中的函数时,我无法计算出生命周期。
struct Alg<'a, 'b, 'c> {
alg1: &'c Fn(&'a A<'a>, &'b B<'b>) -> usize,
alg2: &'c Fn(&'a A<'a>, &'b B<'b>) -> String,
}
struct A<'a> {
a_str: &'a str,
}
struct B<'b> {
b_str: &'b str,
}
fn concat<'a, 'b>(_a: &'a A<'a>, _b: &'b B<'b>) -> String {
_a.a_str.to_string() + &_b.b_str.to_string()
}
fn length<'a, 'b>(_a: &'a A<'a>, _b: &'b B<'b>) -> usize {
_a.a_str.len() + _b.b_str.len()
}
fn run1<'a, 'b, 'c>(_a: &'a A<'a>, _b: &'b B<'b>, _f_c: &'c Alg<'a, 'b, 'c>) {
println!("{}", &(_f_c.alg1)(_a, _b));
}
fn run2<'a, 'b, 'c>(_a: &'a A<'a>, _b: &'b B<'b>, _f_c: &'c Alg<'a, 'b, 'c>) {
println!("{}", &(_f_c.alg2)(_a, _b));
}
fn main() {
let f_struct = Alg {
alg1: &length,
alg2: &concat,
};
for _i in 0..2 {
let a_str = "ABC";
let a = A { a_str: a_str };
for _j in 0..2 {
let b_str = "BCD";
let b = B { b_str: b_str };
println!("{}", concat(&a, &b)); // This works
println!("{}", (f_struct.alg1)(&a, &b)); // I expect that `concat` or `length` in `f_struct` may finished borrowing `a` or `b' here, as like as `println!("{}",concat(&a,&b))`
//run1(&a,&b,&f_struct);
//run2(&a,&b,&f_struct);
}
}
}
当我运行它时,我收到一条错误消息,例如:
error[E0597]: `a` does not live long enough
--> src/main.rs:43:44
|
43 | println!("{}", (f_struct.alg1)(&a, &b)); // I expect that `concat` or `length` in `f_struct` may finished borrowing `a` or `b' here, as like as `println!("{}",concat(&a,&b))`
| --------------- ^^ borrowed value does not live long enough
| |
| borrow used here, in later iteration of loop
...
47 | }
| - `a` dropped here while still borrowed
error[E0597]: `b` does not live long enough
--> src/main.rs:43:48
|
43 | println!("{}", (f_struct.alg1)(&a, &b)); // I expect that `concat` or `length` in `f_struct` may finished borrowing `a` or `b' here, as like as `println!("{}",concat(&a,&b))`
| --------------- ^^ borrowed value does not live long enough
| |
| borrow used here, in later iteration of loop
...
46 | }
| - `b` dropped here while still borrowed
println!("{}",concat(&a,&b))
和 和有什么不一样println!("{}",(f_struct.alg1)(&a,&b))
?
我认为我必须指出函数不再借用生命周期'a
或的值'b
,但我无法从 rust-by-example 或 rust-book 中找到它。
我试图应用强制'c: 'a + 'b
,但这似乎无济于事。
这些问题是相关的,但对我来说不是很清楚。
观点
- 我想在结构中存储函数
- 我可以尝试另一种方式,例如不在结构中存储函数
- 但我想了解这种方法不可能的原因
解决方案
推荐阅读
- sql - 当所有孩子共享相同的值时查找父母ID
- php - WooCommerce:自定义字段(订单评论)到确认电子邮件
- java - 测试 PBEKeySpec junit
- javascript - 在数组中添加多个值
- audio - 多个文件音频不同步的ffmpeg concat
- php - 无法更改 laravel 数据库
- autohotkey - 用于保存对话框的 AHK:导航到桌面并跳转到字段文件名
- android - Kotlin 中 TextInput 的 SetOnKeyListener 不起作用
- javascript - KeysPressed 是位掩码的。如何取消位掩码并使其成为关键状态的结构?(Javascript)
- mysql - HikariCP 和 mysql 线程连接