Yor*_*ian 1 struct vector ownership rust
我正在尝试学习 Rust,并利用代码的出现来做到这一点。我刚刚开始并决定拥有一个包含“Elf”结构的向量,其中每个结构都包含一个向量 calory_items。
我正在尝试从文本文件创建它并具有以下代码:
use std::io::{self, BufReader};
use std::path::Path;
use std::io::prelude::*;
use std::fs::File;
struct Elf {
calory_items: Vec<i32>
}
fn parse_meal_list(source: &str) -> Vec<Elf> {
let file = File::open(source).unwrap();
let file = BufReader::new(file);
let mut elves: Vec<Elf> = Vec::new();
let mut elf = Elf {
calory_items: Vec::new()
};
for line in file.lines() {
let line = line.unwrap();
if line.is_empty() {
// create new Elf
if elf.calory_items.len() > 0 {
// in case there are two empty lines
elves.push(elf);
let mut elf: Elf = Elf { calory_items: Vec::new() };
}
} else {
// append to current Elf object the calories
let calory_item: i32 = line.parse().unwrap();
elf.calory_items.push(calory_item)
}
}
return elves;
}
fn main() {
let input_day_1_source = Path::new("input_files/day_1.txt");
let input_day_1_source = input_day_1_source.to_str().unwrap();
let Elves: Vec<Elf> = parse_meal_list(input_day_1_source);
}
Run Code Online (Sandbox Code Playgroud)
编译器给我以下错误:
error[E0382]: borrow of moved value: `elf`
--> src/main.rs:23:16
|
15 | let mut elf = Elf {
| ------- move occurs because `elf` has type `Elf`, which does not implement the `Copy` trait
...
19 | for line in file.lines() {
| ------------------------ inside of this loop
...
23 | if elf.calory_items.len() > 0 {
| ^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
24 | // in case there are two empty lines
25 | elves.push(elf);
| --- value moved here, in previous iteration of loop
Run Code Online (Sandbox Code Playgroud)
我读了关于借用检查器的 Rust 书,但不知道如何将一个项目附加到列表中并返回所有权(或以其他方式解决它)。
我假设:
let mut elf: Elf = Elf { calory_items: Vec::new() };
Run Code Online (Sandbox Code Playgroud)
elf您打算再次用空进行初始化Elf。但这并不能达到你想要的效果。相反,它创建一个单独的变量来遮蔽elf,使其无法被块的其余部分访问,但不会更改原始elf变量。您需要使用赋值:
elf = Elf { calory_items: Vec::new() };
Run Code Online (Sandbox Code Playgroud)