Missing lifetime specifier when returning Vec> of strings from a file.

huangapple go评论75阅读模式
英文:

Missing lifetime specifier when returning Vec<Vec<&str>> of strings from a file

问题

Here's the translated code part without the error message:

pub fn ParseWords() -> Vec<Vec<&str>> {
    let file = File::open("./words.txt".to_string()).unwrap();
    let mut words = Vec::new();

    // Iterate over the lines of the file.
    for line in io::BufReader::new(file).lines() {
        words.push(line.unwrap().split("|").collect::<Vec<&str>>());
    }

    // Do a bit of shuffling.
    let mut rng = thread_rng();
    words.shuffle(&mut rng);

    return words.clone();
}
英文:

I am trying to write a function that iterates over a text file line by line and splits the sentences into a vector. Then those split lines are put in another vector and returned.

use std::fs::File;
use std::io::{ self, BufRead };

use rand::seq::SliceRandom;
use rand::thread_rng;


pub fn ParseWords() -&gt; Vec&lt;Vec&lt;&amp;str&gt;&gt; {
    let file = File::open(&quot;./words.txt&quot;.to_string()).unwrap();
    let mut words = Vec::new();

    // Iterate over the lines of the file.
    for line in io::BufReader::new(file).lines() {
        words.push(line.unwrap().split(&quot;|&quot;).collect::&lt;Vec&lt;&amp;str&gt;&gt;());
    }

    // Do a bit of shuffling.
    let mut rng = thread_rng();
    words.shuffle(&amp;mut rng);

    return words.clone()
}

I have went down a rabbit hole putting in the compiler's suggestions and consulted chatgpt but I am not really getting anywhere. When compiling I'm getting this:

error[E0106]: missing lifetime specifier
 --&gt; src\parser.rs:8:32
  |
8 | pub fn ParseWords() -&gt; Vec&lt;Vec&lt;&amp;str&gt;&gt; {
  |                                ^ expected named lifetime parameter
  |
  = help: this function&#39;s return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `&#39;static` lifetime
  |
8 | pub fn ParseWords() -&gt; Vec&lt;Vec&lt;&amp;&#39;static str&gt;&gt; {
  |                                

答案1

得分: 2

每当一个函数的参数中没有生命周期,并且返回非静态生命周期时,几乎肯定存在某种问题。你可能唯一会看到这种情况是在 Box::leak 中,它用于泄漏内存。但这里不适用。

所以,你需要返回拥有所有权的值。&str 的拥有版本是 String,所以函数返回值变为 Vec<Vec<String>>

然后,你需要更改你的迭代器以创建字符串。

line.unwrap().split('|').map(|s| s.to_string()).collect()

清理其他所有内容,我们得到:

pub fn parse_words() -> Vec<Vec<String>> {
    let file = File::open("./words.txt").unwrap();

    // 遍历文件的各行。
    let mut words: Vec<Vec<_>> = io::BufReader::new(file)
        .lines()
        .map(|line| line.unwrap().split('|').map(|s| s.to_string()).collect())
        .collect();

    // 做一些混洗。
    let mut rng = thread_rng();
    words.shuffle(&mut rng);

    words
}
英文:

Whenever a function has no lifetimes in its arguments and returns a non-static lifetime, you're almost certainly doing something wrong. The only time you're likely to see it is in Box::leak, which is used to leak memory. That's not applicable here.

So, you need to return owned values. The owned version of &amp;str is String, so the function return becomes Vec&lt;Vec&lt;String&gt;&gt;.

Then you need to change your iterator to make strings.

line.unwrap().split(&#39;|&#39;).map(|s| s.to_string()).collect()

Cleaning up everything else, we get:

pub fn parse_words() -&gt; Vec&lt;Vec&lt;String&gt;&gt; {
    let file = File::open(&quot;./words.txt&quot;).unwrap();

    // Iterate over the lines of the file.
    let mut words: Vec&lt;Vec&lt;_&gt;&gt; = io::BufReader::new(file)
        .lines()
        .map(|line| line.unwrap().split(&#39;|&#39;).map(|s| s.to_string()).collect())
        .collect();

    // Do a bit of shuffling.
    let mut rng = thread_rng();
    words.shuffle(&amp;mut rng);

    words
}

huangapple
  • 本文由 发表于 2023年5月25日 03:12:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定