可变字符串的生存时间不足以执行for循环

时间:2018-06-05 17:46:11

标签: rust

我正在尝试从输入文件中获取一个字符串,并将信息解析为HashMap个结构:

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变量需要在函数返回后生存?

1 个答案:

答案 0 :(得分:5)

c_num: &'static str,

这一行表示Student有一个成员c_num,它是对永远存在的字符串的引用。

您从文件中读出的字符串不会永远存在。它一直存在到循环迭代结束。

您可能希望c_num属于String类型,以便结构拥有该值。