rust - 可变字符串的寿命不足以执行 for 循环
问题描述
我正在尝试从输入文件中获取一个字符串并将信息解析为一个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
函数返回后变量需要存活?
解决方案
c_num: &'static str,
这行说Student
有一个 member c_num
,它是对一个永远存在的字符串的引用。
您从文件中读出的字符串不会永远存在。它一直存在到循环迭代结束。
您可能希望c_num
成为 type String
,以便结构拥有该值。
推荐阅读
- laravel - 让值在 Payfast 中传递
- php - 检查 PHP 中两个数组中的值是否相同(即使值的顺序不同)
- boolean - 在 LabVIEW 2018 的案例结构中将二进制转换为十进制
- python - 在 Python 中的条件下替换数据框列中的 Impute Resample 值
- sql - 如何从具有许多前缀/命名空间的 xml 中获取数据
- qnx - 是否可以在基于微内核的 VMM 上运行具有本机/完全虚拟化的 QNX neutrino RTOS?
- reactjs - 将 react-draft-wyswig 连接到 redux-form
- carousel - 是否可以仅在鼠标悬停时防止 Bootstrap 轮播播放?
- php - 在更高的计算机配置 PHP 中执行时间不会减少
- typescript - 如何不使用打字稿复制代码?