小编Lam*_*dba的帖子

返回捕获引用的高级闭包

我正在尝试在返回闭包的结构上编写一个方法。此闭包应将&[u8]具有任意生命周期的 a'inner作为参数并返回相同的类型&'inner [u8]。为了执行它的功能,闭包还需要一个对 struct 成员的(共享)引用&self。这是我的代码:

#![warn(clippy::pedantic)]

// placeholder for a large type that I can't afford to clone
struct Opaque(usize);

struct MyStruct<'a>(Vec<&'a Opaque>);

impl<'a> MyStruct<'a> {
    pub fn get_func_for_index(
        &'a self,
        n: usize,
    ) -> Option<impl for<'inner> Fn(&'inner [u8]) -> &'inner [u8] + 'a> {
        // the reference to the struct member, captured by the closure
        let opaque: &'a Opaque = *self.0.get(n)?;

        Some(move |i: &[u8]| {
            // placeholder: do something with the …
Run Code Online (Sandbox Code Playgroud)

rust

4
推荐指数
1
解决办法
82
查看次数

标签 统计

rust ×1