gpt4 book ai didi

vector - 需要矢量切片才能活得更久

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

有没有办法让这个向量的切片持续足够长的时间,以便我可以在这种循环结构中使用它们?

fn populate_chain(file_path: &str) -> HashMap<String, HashSet<&String>> {
println!("loading...");
let time = util::StopWatch::new();
let mut words = HashMap::new();
{
let f = |mut x: Vec<String>| {
let word = x.pop().unwrap();
words.insert(word, HashSet::new());
};
Csv::process_rows(f, file_path, "\t");
}

let col: Vec<(String, HashSet<&String>)> = words.clone().into_iter().collect();
let m: usize = col.len() - 1;
for i in 0..m {
let ref k: String = col[i].0;
for j in i..m {
let ref nk: String = col[j].0;
if check_link(k, nk) {
words.get_mut(k).unwrap().insert(nk);
words.get_mut(nk).unwrap().insert(k);
}
}
}

time.print_time();
words
}

我使用双 for 循环将相关的单词链接在一起,以便以后可以快速查找它们。

这是编译器错误...

error: `col` does not live long enough
--> src/main.rs:28:29
|
28 | let ref k: String = col[i].0;
| ^^^ does not live long enough
...
40 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the block at 13:72...
--> src/main.rs:13:73
|
13 | fn populate_chain(file_path: &str) -> HashMap<String, HashSet<& String>>{
| ^

error: `col` does not live long enough
--> src/main.rs:30:34
|
30 | let ref nk: String = col[j].0;
| ^^^ does not live long enough
...
40 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the block at 13:72...
--> src/main.rs:13:73
|
13 | fn populate_chain(file_path: &str) -> HashMap<String, HashSet<& String>>{
|

最佳答案

我可以从您的函数签名中告诉您,您在尝试编写此函数时会遇到大问题,至少如果您希望它包含非空 HashSet 的话。 s 在结果中。

fn populate_chain(file_path: &str) -> HashMap<String, HashSet<&String>>

这个函数签名里面有引用;他们已经消逝了一生。如果您将推断的生命周期明确化,它将如下所示:

fn populate_chain<'a>(file_path: &'a str) -> HashMap<String, HashSet<&'a String>>

换句话说:这个函数声称,给定一些生命周期为 'a 的字符串切片,它将返回一个包含 String 的集合具有生命周期的对象 'a .

但是你没有办法分配这样的 String代码中的对象。 :(

所以,你被困住了;无论您在该函数体中放入什么,您都无法提供返回关于 HashSet 的重要结果的实现。

然而,一切并没有丢失。例如,您可以修改您的函数,以便它也将对 TypedArena 的引用作为附加参数。具有适当的生命周期,然后在那里分配字符串。另一个(更简单的)选项是使用 HashSet<String>而不是 HashSet<&String> ...

关于vector - 需要矢量切片才能活得更久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600519/

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