首页 > 解决方案 > 从存储在结构中引用的函数不会放弃所有权

问题描述

我正在编写一个算法测试平台来比较 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,但这似乎无济于事。

这些问题是相关的,但对我来说不是很清楚。

观点

标签: functionrustlifetime

解决方案



推荐阅读