0

I have this function

pub struct Config {
    pub query: String,
    pub filename: String,
}

impl Config {
    pub fn new(args: &Vec<String>) -> Result<Config, &str> {
        if args.len() > 3 {
            return Err("Error");
        }

        let query = args[1].clone();
        let filename = args[2].clone();
        Ok(Config {query, filename})
    }
}

pub fn run(config: &Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.filename)?;
    for i in search(&config.query, &contents) {
        println!("Found: {}", i);
    }
    Ok(())
}

I got an error "cannot move out of config.filename which is behind a shared reference" when run this

if let Err(e) = run(&config) {
    println!("Error:{}", e);
    process::exit(1);
}

run(&config);

I really don't know why I got this error. Can anyone please explain it? Many thanks.

Jmb
  • 18,893
  • 2
  • 28
  • 55
abc
  • 69
  • 1
  • 4
  • Try `fs::read_to_string(&config.filename)` – Jmb Oct 14 '21 at 06:43
  • Can you please explain why this error happen? I don't understand. Thanks – abc Oct 14 '21 at 07:58
  • Does this answer your question? [Cannot move out of borrowed content / cannot move out of behind a shared reference](https://stackoverflow.com/questions/28158738/cannot-move-out-of-borrowed-content-cannot-move-out-of-behind-a-shared-referen) – Svetlin Zarev Oct 14 '21 at 08:27
  • It would be helpful to those trying to answer your question if you would include the full output of `cargo build`. This would include the error message as well as point to the particular line of code where the error is occuring. – tjheslin1 Oct 15 '21 at 09:05

1 Answers1

0

When you call read_to_string(config.filename), you're moving filename (i.e. transferring ownership) into read_to_string. But you don't have ownership since run only borrows config.

Since read_to_string actually takes AsRef<Path> (i.e. anything that can be referenced as a Path), it can work with a borrowed string as well as an owned one. So you can solve the issue by simply lending filename: read_to_string (&config.filename).

Jmb
  • 18,893
  • 2
  • 28
  • 55