0

I'm writing a ASCII Pokémon game and have come across a ownership error:

use std::fs::File;
use std::io::{BufRead, BufReader};

pub fn parse_map(filename: &str) -> (Vec<String>, Vec<String>) {
    let file = File::open(filename).unwrap();
    let reader = BufReader::new(file);

    let mut map_vec = Vec::new();
    let mut portal_vec = Vec::new();

    let mut reading_map = false;
    let mut reading_portals = false;

    for (index, line) in reader.lines().enumerate() {
        let read_line = line.unwrap();

        if read_line == "end" {
            reading_map = false;
            reading_portals = false;
        }

        if reading_map {
            map_vec.push(read_line);
        }
        if reading_portals {
            portal_vec.push(read_line);
        }

        if read_line == "map" {
            reading_map = true;
        }
        if read_line == "portals" {
            reading_portals = true;
        }
    }

    return (map_vec, portal_vec);
}

and here are the errors

error[E0382]: use of moved value: `read_line`
  --> src/lib.rs:26:29
   |
15 |         let read_line = line.unwrap();
   |             --------- move occurs because `read_line` has type `std::string::String`, which does not implement the `Copy` trait
...
23 |             map_vec.push(read_line);
   |                          --------- value moved here
...
26 |             portal_vec.push(read_line);
   |                             ^^^^^^^^^ value used here after move
...
35 |     }
   |     - value moved here, in previous iteration of loop

error[E0382]: borrow of moved value: `read_line`
  --> src/lib.rs:29:12
   |
15 |         let read_line = line.unwrap();
   |             --------- move occurs because `read_line` has type `std::string::String`, which does not implement the `Copy` trait
...
23 |             map_vec.push(read_line);
   |                          --------- value moved here
...
26 |             portal_vec.push(read_line);
   |                             --------- value moved here
...
29 |         if read_line == "map" {
   |            ^^^^^^^^^ value borrowed here after move
...
35 |     }
   |     - value moved here, in previous iteration of loop
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
  • 1
    The easiest fix is `map_vec.push(read_line.clone())` and `portal_vec.push(read_line.clone())` – Shepmaster Jul 21 '20 at 13:38
  • thank you, this worked! I will be able to solve this error myself in the future now – William Davies Jul 21 '20 at 13:40
  • You are welcome! Note that this isn't the only solution for every possible "use of moved value" error. What's important is realizing that `read_line` is gone and you don't have access to it any more. [Here's another version where there are no added clones](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=147d9fe2466d55bb5984322ec83c7ae6). – Shepmaster Jul 21 '20 at 13:47

0 Answers0