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.
Option
Result
i32
Result<i32, String>
String
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?
contents
map
std::io::Result<usize>
Read::read_to_string
move
, , , ,
. , .
, , , (self, &self, &mut self). , , , . , , .
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)); } }
Source: https://habr.com/ru/post/1651039/More articles:viewdidload вызвано после закрытия отклонения дочернего viewcontroller - iosrequestLayout () is incorrectly called CollapsingToolbarLayout - androidAny difference between clock_gettime (CLOCK_REALTIME ....) and time ()? - c ++How to update JSONArray value in java - javaExpress server does not close - node.jsОбъединение исходных файлов Angular 2.0 в один файл поставщика для развертывания - javascriptHow to accept mixin template as argument? - c ++Maximum packet length for Bluetooth LE? - bluetooth-lowenergyThe difference between the md-whiteframe directive and the md-whiteframe css class - angularjsGTK + same user interface theme for all platforms - c ++All Articles