Why is the value here moved to close rather than borrowed?

The section "Error Handling" in the book of rust contains an example of the use of combinators Optionand Result. The file is read, and through the combinatorial series application, the contents are analyzed as i32it is returned to Result<i32, String>. Now I was confused when I looked at the code. There, in one closure for and_then, a local value is created String, which is subsequently passed as a return value to another combinator.

Here is a sample code:

use std::fs::File;
use std::io::Read;
use std::path::Path;

fn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> {
    File::open(file_path)
         .map_err(|err| err.to_string())
         .and_then(|mut file| {
              let mut contents = String::new(); // local value
              file.read_to_string(&mut contents)
                  .map_err(|err| err.to_string())
                  .map(|_| contents) // moved without 'move'
         })
         .and_then(|contents| {
              contents.trim().parse::<i32>()
                      .map_err(|err| err.to_string())
         })
         .map(|n| 2 * n)
}

fn main() {
    match file_double("foobar") {
        Ok(n) => println!("{}", n),
        Err(err) => println!("Error: {}", err),
    }
}

, , contents. map, std::io::Result<usize> Read::read_to_string. : , , move, , , contents . . , String contents , , . move?

+4
1

, , , ,

. , .

, , , (self, &self, &mut self). , , , . , , .

- , . .

, , . , .


move , . , . , , :

fn main() {
    let a = 1;
    let b = 2;

    {
        let b = &b;
        needs_to_own_a(move || a_function(a, b));
    }
}
+3

Source: https://habr.com/ru/post/1651039/


All Articles