gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:24:20 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com