У этого вопроса уже есть ответ:
- Cannot split a string into string slices with explicit lifetimes because the string does not live long enough 2 ответа
- Why does my variable not live long enough? 1 ответ
Я пытаюсь взять строку из входного файла и проанализировать информацию в HashMap
struct:
use std::{fs::File, io::prelude::*};pub struct Student {
c_num: &'static str,
cla: i32,
ola: i32,
quiz: i32,
exam: i32,
final_exam: i32,
}impl Student {
pub fn new(
c_num: &'static str,
cla: i32,
ola: i32,
quiz: i32,
exam: i32,
final_exam: i32,
) -> Student {
Student {
c_num: c_num,
cla: cla,
ola: ola,
quiz: quiz,
exam: exam,
final_exam: final_exam,
}
} pub fn from_file(filename: String) -> Vec<Student> {
let mut f = File::open(filename).expect("File not found");
let mut contents = String::new(); f.read_to_string(&mut contents); let mut students: Vec<Student> = Vec::new(); for i in contents.lines().skip(1) {
let mut bws = i.split_whitespace();
let stdnt: Student = Student::new(
bws.next().unwrap(),
bws.next().unwrap().parse().unwrap(),
bws.next().unwrap().parse().unwrap(),
bws.next().unwrap().parse().unwrap(),
bws.next().unwrap().parse().unwrap(),
bws.next().unwrap().parse().unwrap(),
); students.insert(0, stdnt);
} students
}
}fn main() {}
Когда я пытаюсь скомпилировать, компилятор мне это дает.
error[E0597]: `contents` does not live long enough
--> src/main.rs:39:18
|
39 | for i in contents.lines().skip(1) {
| ^^^^^^^^ borrowed value does not live long enough
...
54 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
Почему contents
нужно продолжать жить после возвращения функции?
В этой строке указано, что
Student
имеет членc_num
, который является ссылкой на строку, которая живет вечно.Строка, которую вы читаете из файла, не вечна. Он живет до конца итерации цикла.
Вероятно, вы хотите, чтобы
c_num
имел типString
, так что структура владеет значением.