【发布时间】:2020-04-20 06:00:43
【问题描述】:
所以,我正在努力将我用 Python 编写的字符串标记器移植到 Rust,但我遇到了一个我似乎无法解决生命周期和结构的问题。
所以,流程基本上是:
- 获取文件数组
- 将每个文件转换为
Vec<String>的令牌 - 使用
Counter和Unicase从每个vec获取单个令牌实例的计数 - 将该计数与其他一些数据一起保存在结构中
- (未来)对结构集进行一些处理,以在每个文件数据旁边累积总数据
struct Corpus<'a> {
words: Counter<UniCase<&'a String>>,
parts: Vec<CorpusPart<'a>>
}
pub struct CorpusPart<'a> {
percent_of_total: f32,
word_count: usize,
words: Counter<UniCase<&'a String>>
}
fn process_file(entry: &DirEntry) -> CorpusPart {
let mut contents = read_to_string(entry.path())
.expect("Could not load contents.");
let tokens = tokenize(&mut contents);
let counted_words = collect(&tokens);
CorpusPart {
percent_of_total: 0.0,
word_count: tokens.len(),
words: counted_words
}
}
pub fn tokenize(normalized: &mut String) -> Vec<String> {
// snip ...
}
pub fn collect(results: &Vec<String>) -> Counter<UniCase<&'_ String>> {
results.iter()
.map(|w| UniCase::new(w))
.collect::<Counter<_>>()
}
但是,当我尝试返回 CorpusPart 时,它抱怨它正在尝试引用局部变量 tokens。我该如何/应该如何处理这个问题?我尝试添加生命周期注释,但无法弄清楚...
基本上,我不再需要Vec<String>,但我确实需要其中一些用于柜台的String。
感谢您的帮助,谢谢!
【问题讨论】:
-
我们能否获得您的代码 sn-p 的几乎可编译版本(即唯一的错误是生命周期)?尽管乍一看,我相信您可以删除
CorpusPart中的字符串引用(以及大多数其他字符串引用),因为您不再需要旧的 Vec。稍后我会发布正确的答案。
标签: rust lifetime-scoping