创建关闭返回字符串的迭代器 [英] Create closure returning iterator on string

查看:50
本文介绍了创建关闭返回字符串的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to write a closure that takes an object and returns an iterator from it. The idea is to store the closure in a structure and apply as needed:

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并删除拳击,但结果是相同的.

I tried to change String to Vec and remove boxing, but the result is the same.

如何使它编译?

推荐答案

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

Closures with borrows in parameter or return types have some known bugs as shown in this issue report and the others it links to: https://github.com/rust-lang/rust/issues/58052

有几种方法可以解决此问题.

There are a few ways to work around the issue.

使用完全限定的语法

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

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

在封闭体

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);
    }
}

这篇关于创建关闭返回字符串的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆