gpt4 book ai didi

rust - 无法返回 Chars 迭代器,因为它是 "does not live long enough"

转载 作者:行者123 更新时间:2023-11-29 08:35:51 25 4
gpt4 key购买 nike

我希望能够将 Chars 迭代器分配给一个结构,该结构的 String 是在该结构的“构造函数”方法内部创建的。我该怎么做?

代码(run it):

use std::str::Chars;

fn main() {
let foo = Foo::new();
}

struct Foo<'a> {
chars: Chars<'a>
}
impl<'a> Foo<'a> {
pub fn new() -> Self {
let s = "value".to_string();
Foo { chars: s.chars() }
}
}

错误:

error: `s` does not live long enough
--> <anon>:13:22
13 |> Foo { chars: s.chars() }
|> ^
note: reference must be valid for the lifetime 'a as defined on the block at 11:25...
--> <anon>:11:26
11 |> pub fn new() -> Self {
|> ^
note: ...but borrowed value is only valid for the block suffix following statement 0 at 12:36
--> <anon>:12:37
12 |> let s = "value".to_string();
|>

(在我的真实代码中,构造函数从文件中读取文本)

最佳答案

你不能。 Chars 不拥有字符串的所有权,所以一旦你离开 Foo::new,字符串就不再存在了。您需要存储字符串本身。 Chars 实际上只是一种小型实用程序类型,旨在在现场使用,而不是存储在某个地方供以后使用。

关于rust - 无法返回 Chars 迭代器,因为它是 "does not live long enough",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556455/

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