rust - 在字符串上创建闭包返回迭代器

标签 rust iterator closures lifetime

我想编写一个闭包,它接受一个对象并从中返回一个迭代器。这个想法是将闭包存储在一个结构中并根据需要应用:

fn main() {
    let iter_wrap = |x: &String| Box::new(x.chars());
    let test = String::from("test");

    for x in iter_wrap(&test) {
        println!("{}", x);
    }
}

这会导致错误:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
 --> src/main.rs:2:45
  |
2 |     let iter_wrap = |x: &String| Box::new(x.chars());
  |                                             ^^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 2:21...
 --> src/main.rs:2:21
  |
2 |     let iter_wrap = |x: &String| Box::new(x.chars());
  |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
 --> src/main.rs:2:43
  |
2 |     let iter_wrap = |x: &String| Box::new(x.chars());
  |                                           ^
note: but, the lifetime must be valid for the call at 5:14...
 --> src/main.rs:5:14
  |
5 |     for x in iter_wrap(&test) {
  |              ^^^^^^^^^^^^^^^^
note: ...so that argument is valid for the call
 --> src/main.rs:5:14
  |
5 |     for x in iter_wrap(&test) {
  |              ^^^^^^^^^^^^^^^^

我尝试将 String 更改为 Vec 并删除装箱,但结果是一样的。

如何让它编译?

最佳答案

在参数或返回类型中借用的闭包有一些已知错误,如本问题报告及其链接的其他错误所示:https://github.com/rust-lang/rust/issues/58052

有几种方法可以解决这个问题。

Using fully qualified syntax

fn main() {
    let iter_wrap = |x| Box::new(str::chars(x));
    let test = String::from("test");

    for x in iter_wrap(&test) {
        println!("{}", x);
    }
}

Using a type annotation in the closure body

fn main() {
    let iter_wrap = |x| {let x: &String = x; Box::new(x.chars()) };
    let test = String::from("test");

    for x in iter_wrap(&test) {
        println!("{}", x);
    }
}

关于rust - 在字符串上创建闭包返回迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56724730/

相关文章:

python - 使用 ECB 模式加密解密字节时出现问题

string - 为什么在使用 Vec::contains 时 &str 不强制转换为 &String?

c++ - 将通用模板类作为仿函数参数传递

java - 遍历集合集合

javascript - Mithril 组件组合中单独单击增量按钮

go - 使用什么语言编写游戏库,Go 还是 Rust?

windows - 如何从规范的 Windows 路径中删除\\?\前缀?

ruby - 在 Ruby 中更新哈希值

swift - 将具有多个参数的函数分配给变量

javascript - 这些闭包示例有什么区别?