0

考虑下一个代码:

fn get_ref<'a, R>(slice: &'a Vec<i32>, f: fn(&'a Vec<i32>) -> R) -> R
where
    R: 'a,
{
    f(slice)
}

fn main() {
    let v = [1,2,3,4,5,6];
    let iter = get_ref(&v, |x| x.iter().skip(1).take(2));

    println!("{:?}", iter.collect::<Vec<_>>());
}

我创建了一些static变量,然后将一些函数应用于它的引用并得到结果。它似乎工作得很好。至少它成功编译。

现在我正在尝试添加下一个抽象级别。事情变得越来越奇怪......

fn owned<'a, R>(owner: Vec<i32>, f: fn(&'a Vec<i32>) -> R)
where
    R: 'a,
{
    let _ = get_ref(&owner, f); // error occurs here
    // `owner` does not live long enough.
}

// get_ref is the same as in the first example
fn get_ref<'a, R>(slice: &'a Vec<i32>, f: fn(&'a Vec<i32>) -> R) -> R
where
    R: 'a,
{
    f(slice)
}

fn main() {
    let v = [1,2,3,4,5,6];
    owned(v, |x| x.iter().skip(1).take(2));
}

对我来说,它看起来几乎是相同的代码。但是 Rust 无法编译它。我真的不明白为什么会这样,我应该如何重写我的代码来编译。

4

1 回答 1

0

想象一下,如果我决定调用定义为的owned<'static, i32>(Vec<i32>, foo)函数foo

fn foo(vec: &'static Vec<i32>) -> i32 { ... }

这满足owned,因为的界限i32: 'static。然而,这意味着你必须有一个静态引用 call f,但owner不会永远存在,因为它在 结束时被销毁owned

解决它的一种方法是使用以下方法:

fn owned<R>(owner: Vec<i32>, f: for<'a> fn(&'a Vec<i32>) -> R) {
    let _ = get_ref(&owner, f);
}

它说f必须可以在任何生命周期内调用,而不仅仅是某个特定的生命周期。但是,这具有R不能从参数中借用的结果,因为R在比 更大的范围内声明'a。在保持泛型不变的同时,没有任何方法可以解决这个问题。


这个答案取自我对 URLO 上的这个帖子的回复。

于 2021-02-21T19:53:47.633 回答