如何从关闭中取回移动值的所有权?

suy*_*ash 6 rust

考虑以下程序:

fn primes_up_to(n: usize) -> Vec<usize> {
    let mut ans = Vec::with_capacity(n);

    if n < 2 {
        return ans;
    }

    ans.push(2);

    // https://doc.rust-lang.org/1.22.0/book/first-edition/closures.html#closures-and-their-environment
    // The closure needs ownership of vec to access elements
    let is_prime = |n: usize| -> bool {
        for x in ans {
            if x * x > n {
                break;
            }

            if n % x == 0 {
                return false;
            }
        }

        true
    };

    let mut i = 3;
    while i <= n {
        if is_prime(i) {
            ans.push(i);
        }

        i += 2;
    }

    ans
}

fn main() {
    println!("{:?}", primes_up_to(23));
}
Run Code Online (Sandbox Code Playgroud)

游乐场

编译上面的代码会出现以下编译错误:

fn primes_up_to(n: usize) -> Vec<usize> {
    let mut ans = Vec::with_capacity(n);

    if n < 2 {
        return ans;
    }

    ans.push(2);

    // https://doc.rust-lang.org/1.22.0/book/first-edition/closures.html#closures-and-their-environment
    // The closure needs ownership of vec to access elements
    let is_prime = |n: usize| -> bool {
        for x in ans {
            if x * x > n {
                break;
            }

            if n % x == 0 {
                return false;
            }
        }

        true
    };

    let mut i = 3;
    while i <= n {
        if is_prime(i) {
            ans.push(i);
        }

        i += 2;
    }

    ans
}

fn main() {
    println!("{:?}", primes_up_to(23));
}
Run Code Online (Sandbox Code Playgroud)

我知道一个潜在的解决方案是将ans( &ans)的不可变引用传递给is_prime. 每次我调用时退出时,所有权ans传递is_prime和返回的惯用方式是什么? is_primeis_prime

She*_*ter 4

\n

如何从闭包中取回移动值的所有权

\n
\n\n

你不知道

\n\n

一旦所有权转移,它就消失了。“取回它”的唯一方法是让现在拥有它的东西将其转移回来。into_inner出于这个确切原因,某些类型有一个方法。其他类型也有等效的方法。

\n\n

根据定义,闭包的唯一接口是调用它的能力。没有其他方法的可能性。

\n\n

完成后您可以返回捕获的值,但这对您的情况没有帮助,因为您需要多次调用闭包 \xe2\x80\x94\xc2\xa0you 无法返回它,因为它可能是将来需要的。

\n