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

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

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

问题

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

  1. pub fn ParseWords() -> Vec<Vec<&str>> {
  2. let file = File::open("./words.txt".to_string()).unwrap();
  3. let mut words = Vec::new();
  4. // Iterate over the lines of the file.
  5. for line in io::BufReader::new(file).lines() {
  6. words.push(line.unwrap().split("|").collect::<Vec<&str>>());
  7. }
  8. // Do a bit of shuffling.
  9. let mut rng = thread_rng();
  10. words.shuffle(&mut rng);
  11. return words.clone();
  12. }
英文:

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.

  1. use std::fs::File;
  2. use std::io::{ self, BufRead };
  3. use rand::seq::SliceRandom;
  4. use rand::thread_rng;
  5. pub fn ParseWords() -&gt; Vec&lt;Vec&lt;&amp;str&gt;&gt; {
  6. let file = File::open(&quot;./words.txt&quot;.to_string()).unwrap();
  7. let mut words = Vec::new();
  8. // Iterate over the lines of the file.
  9. for line in io::BufReader::new(file).lines() {
  10. words.push(line.unwrap().split(&quot;|&quot;).collect::&lt;Vec&lt;&amp;str&gt;&gt;());
  11. }
  12. // Do a bit of shuffling.
  13. let mut rng = thread_rng();
  14. words.shuffle(&amp;mut rng);
  15. return words.clone()
  16. }

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:

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

答案1

得分: 2

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

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

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

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

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

  1. pub fn parse_words() -> Vec<Vec<String>> {
  2. let file = File::open("./words.txt").unwrap();
  3. // 遍历文件的各行。
  4. let mut words: Vec<Vec<_>> = io::BufReader::new(file)
  5. .lines()
  6. .map(|line| line.unwrap().split('|').map(|s| s.to_string()).collect())
  7. .collect();
  8. // 做一些混洗。
  9. let mut rng = thread_rng();
  10. words.shuffle(&mut rng);
  11. words
  12. }
英文:

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.

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

Cleaning up everything else, we get:

  1. pub fn parse_words() -&gt; Vec&lt;Vec&lt;String&gt;&gt; {
  2. let file = File::open(&quot;./words.txt&quot;).unwrap();
  3. // Iterate over the lines of the file.
  4. let mut words: Vec&lt;Vec&lt;_&gt;&gt; = io::BufReader::new(file)
  5. .lines()
  6. .map(|line| line.unwrap().split(&#39;|&#39;).map(|s| s.to_string()).collect())
  7. .collect();
  8. // Do a bit of shuffling.
  9. let mut rng = thread_rng();
  10. words.shuffle(&amp;mut rng);
  11. words
  12. }

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:

确定