1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/// # 分层错误处理
///
/// 1. Option
/// 2. Error
/// 3. Panic
/// 4. Abort
///
/// Base usage: 使用Option<T>
///
/// ```rust
/// fn get_shortest(names: Vec<&str>) -> Option<&str> {
///     if names.len() > 0 {
///         let mut shortest = names[0];
///         for name in names.iter() {
///             if name.len() < shortest.len() {
///                 shortest = *name;
///             }
///         }
///         Some(shortest)
///    } else {
///        None
///    }
/// }
/// fn show_shortest(names: Vec<&str>) -> &str {
///    match get_shortest(names) {
///        Some(shortest) => shortest,
///        None             => "Not Found",
///    }
/// }
/// fn main(){
///    assert_eq!(show_shortest(vec!["Uku", "Felipe"]), "Uku");
///    assert_eq!(show_shortest(Vec::new()), "Not Found");
/// }
/// ```
///
/// Base usage: 高效处理Option<T>
///
/// ```rust
/// fn get_shortest_length(names: Vec<&str>) -> Option<usize> {
///     match get_shortest(names) {
///         Some(shortest) => Some(shortest.len()),
///         None             => None,
///     }
/// }
/// fn main(){
///     assert_eq!(get_shortest_length(vec!["Uku","Felipe"]),Some(3));
///     assert_eq!(get_shortest_length(Vec::new()), None);
/// }
/// ```
///
/// Base usage: 使用map处理Option<T>
///
/// ```rust
/// fn get_shortest_length(names: Vec<&str>) -> Option<usize> {
///     get_shortest(names).map(|name| name.len())
/// }
/// fn main(){
///     assert_eq!(get_shortest_length(vec!["Uku","Felipe"]),Some(3));
///     assert_eq!(get_shortest_length(Vec::new()), None);
/// }
/// ```
///
/// Base usage: 使用map和and_than处理Option<T>
///
/// ```rust
/// fn double(value: f64) -> f64 {
///     value * 2.
/// }
/// fn square(value: f64) -> f64 {
///     value.powi(2 as i32)
/// }
/// fn inverse(value: f64) -> f64 {
///     value * -1.
/// }
/// fn log(value: f64) -> Option<f64> {
///    match value.log2() {
///        x if x.is_normal() => Some(x),
///        _                      => None
///    }
/// }
/// fn sqrt(value: f64) -> Option<f64> {
///    match value.sqrt() {
///        x if x.is_normal() => Some(x),
///        _                      => None
///    }
/// }
/// fn main () {
///    let number: f64 = 20.;
///    let result = Option::from(number)
///        .map(inverse).map(double).map(inverse)
///        .and_then(log).map(square).and_then(sqrt);
///    match result {
///        Some(x) => println!("Result was {}.", x),
///        None    => println!("This failed.")
///    }
/// }
/// ```
///
/// Base usage: 处理Result<T, E>
///
/// ```rust
/// fn main(){
///     let n = "1";
///     assert_eq!(n.parse::<i32>(), Ok(1));
///     let n = "a";
///     // 输出 Err(ParseIntError { kind: InvalidDigit })
///     println!("{:?}", n.parse::<i32>());
/// }
/// ```
///
/// Base usage: 使用map处理Result<T, E>
///
/// ```rust
/// use std::num::ParseIntError;
/// // fn square(number_str: &str) -> Result<i32, ParseIntError>
/// // {
/// //    number_str.parse::<i32>().map(|n| n.pow(2))
/// // }
/// type ParseResult<T> = Result<T, ParseIntError>;
/// fn square(number_str: &str) -> ParseResult<i32>
/// {
///     number_str.parse::<i32>().map(|n| n.pow(2))
/// }
/// fn main() {
///     match square("10") {
///         Ok(n) => assert_eq!(n, 100),
///         Err(err) => println!("Error: {:?}", err),
///     }
/// }
/// ```
///
/// Base usage: 从文件中读取数字并计算求和,展示统一的错误处理
///
/// 将此代码复制到自定义的io_origin.rs文件里,rustc编译之后在终端执行命令:
///
/// `$ ./io_origin test_txt`
///
/// ```rust
/// use std::env;
/// use std::fs::File;
/// use std::io::prelude::*;
/// fn main() {
///     let args: Vec<String> = env::args().collect();
///     println!("{:?}", args);
///     let filename = &args[1];
///     let mut f = File::open(filename).unwrap();
///     let mut contents = String::new();
///     f.read_to_string(&mut contents).unwrap();
///    let mut sum = 0;
///    for c in contents.lines(){
///        let n = c.parse::<i32>().unwrap();
///        sum += n;
///    }
///    println!("{:?}", sum);
/// }
/// ```
///
/// Base usage: 【重构】从文件中读取数字并计算求和,展示统一的错误处理
///
/// 将此代码复制到自定义的io_origin.rs文件里,rustc编译之后在终端执行命令:
///
/// `$ ./io_origin test_txt`
///
/// ```rust
/// use std::env;
/// use std::error::Error;
/// use std::fs::File;
/// use std::io::prelude::*;
/// use std::process;
/// type ParseResult<i32> = Result<i32, Box<Error>>;
/// fn run(filename: &str) -> ParseResult<i32> {
///     File::open(filename).map_err(|e| e.into())
///     .and_then(|mut f|{
///         let mut contents = String::new();
///         f.read_to_string(&mut contents)
///         .map_err(|e| e.into()).map(|_|contents)
///     })
///     .and_then(|contents|{
///         let mut sum = 0;
///        for c in contents.lines(){
///            match c.parse::<i32>() {
///                Ok(n) => {sum += n;},
///                Err(err) => {
///                    let err: Box<Error> = err.into();
///                    println!("error info: {}, cause: {:?}"
///                    , err.description(),err.cause());
///                },
///                // Err(err) => { return Err(From::from(err));},
///            }
///        }
///        Ok(sum)
///    })
/// }
/// fn main() {
///     let args: Vec<String> = env::args().collect();
///     let filename = &args[1];
///     println!("In file {}", filename);
///     match run(filename) {
///        Ok(n) => { println!("{:?}", n); },
///        Err(e) => {
///            println!("main error: {}", e);
///            process::exit(1);
///        }
///    }
/// }
/// ```
///
/// Base usage: 【再次重构】从文件中读取数字并计算求和,展示统一的错误处理
///
/// 动态分发改为静态分发
///
/// 将此代码复制到自定义的io_origin.rs文件里,rustc编译之后在终端执行命令:
///
/// `$ ./io_origin test_txt`
///
/// ```rust
/// use std::env;
/// use std::error::Error;
/// use std::fs::File;
/// use std::io::prelude::*;
/// use std::process;
/// use std::io;
/// use std::num;
/// use std::fmt;
/// #[derive(Debug)]
/// enum CliError {
///     Io(io::Error),
///     Parse(num::ParseIntError),
/// }
///
/// impl fmt::Display for CliError {
///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
///         match *self {
///             CliError::Io(ref err) => write!(f, "IO error: {}", err),
///             CliError::Parse(ref err) => write!(f, "Parse error: {}", err),
///         }
///     }
/// }
///
/// impl Error for CliError {
///     fn description(&self) -> &str {
///         match *self {
///             CliError::Io(ref err) => err.description(),
///             CliError::Parse(ref err) => Error::description(err),
///         }
///     }
///
///     fn cause(&self) -> Option<&Error> {
///         match *self {
///             CliError::Io(ref err) => Some(err),
///             CliError::Parse(ref err) => Some(err),
///         }
///     }
/// }
/// impl From<io::Error> for CliError {
///     fn from(err: io::Error) -> CliError {
///         CliError::Io(err)
///     }
/// }
/// impl From<num::ParseIntError> for CliError {
///     fn from(err: num::ParseIntError) -> CliError {
///         CliError::Parse(err)
///     }
/// }
/// fn run(filename: Option<String>) -> ParseResult<i32> {
///     let mut file = File::open(filename.unwrap())?;
///
///     let mut contents = String::new();
///     file.read_to_string(&mut contents)?;
///     let mut sum = 0;
///     for c in contents.lines(){
///         let n: i32 = c.parse::<i32>()?;
///         sum += n;
///     }
///     Ok(sum)
/// }
/// type ParseResult<i32> = Result<i32, CliError>;
/// fn main() {
///     let filename = env::args().nth(1);
///     match run(filename) {
///         Ok(n) => {
///             println!("{:?}", n);
///         },
///         Err(e) => {
///             println!("main error: {}", e);
///             process::exit(1);
///         }
///     }
/// }
/// ```
///
/// Base usage: 【三次重构】从文件中读取数字并计算求和,展示统一的错误处理
///
/// 使用try!的简化问号操作符
///
/// 将此代码复制到自定义的io_origin.rs文件里,rustc编译之后在终端执行命令:
///
/// `$ ./io_origin test_txt`
///
/// ```rust
/// use std::env;
/// use std::error::Error;
/// use std::fs::File;
/// use std::io::prelude::*;
/// use std::process;
/// use std::io;
/// use std::num;
/// use std::fmt;
///
/// #[derive(Debug)]
/// enum CliError {
///     Io(io::Error),
///     Parse(num::ParseIntError),
/// }
///
/// impl fmt::Display for CliError {
///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
///         match *self {
///             CliError::Io(ref err) => write!(f, "IO error: {}", err),
///             CliError::Parse(ref err) => write!(f, "Parse error: {}", err),
///         }
///     }
/// }
///
/// impl Error for CliError {
///     fn description(&self) -> &str {
///         match *self {
///             CliError::Io(ref err) => err.description(),
///             CliError::Parse(ref err) => Error::description(err),
///         }
///     }
///
///     fn cause(&self) -> Option<&Error> {
///         match *self {
///             CliError::Io(ref err) => Some(err),
///             CliError::Parse(ref err) => Some(err),
///         }
///     }
/// }
/// impl From<io::Error> for CliError {
///     fn from(err: io::Error) -> CliError {
///         CliError::Io(err)
///     }
/// }
/// impl From<num::ParseIntError> for CliError {
///     fn from(err: num::ParseIntError) -> CliError {
///         CliError::Parse(err)
///     }
/// }
/// fn run(filename: &str) -> ParseResult<i32> {
///     let mut file = File::open(filename)?;
///
///     let mut contents = String::new();
///     file.read_to_string(&mut contents)?;
///     let mut sum = 0;
///     for c in contents.lines(){
///         let n: i32 = c.parse::<i32>()?;
///         sum += n;
///     }
///     Ok(sum)
/// }
/// type ParseResult<i32> = Result<i32, CliError>;
///
/// fn main() {
///     let args: Vec<String> = env::args().collect();
///     let filename = &args[1];
///     println!("In file {}", filename);
///
///     match run(filename) {
///         Ok(n) => {
///             println!("{:?}", n);
///         },
///         Err(e) => {
///             println!("main error: {}", e);
///             process::exit(1);
///         }
///     }
/// }
/// ```
///
/// Base usage: 【四次重构】从文件中读取数字并计算求和,展示统一的错误处理
///
///  使用NoneError
///
/// 将此代码复制到自定义的io_origin.rs文件里,rustc编译之后在终端执行命令:
///
/// `$ ./io_origin test_txt`
///
/// ```rust
/// #![feature(try_trait)]
/// use std::env;
/// use std::error::Error;
/// use std::fs::File;
/// use std::io::prelude::*;
/// use std::process;
/// use std::io;
/// use std::num;
/// use std::fmt;
/// use std::option::NoneError;
///
/// #[derive(Debug)]
/// enum CliError {
///     Io(io::Error),
///     Parse(num::ParseIntError),
///     NoneError(NoneError),
/// }
/// impl fmt::Display for CliError {
///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
///         match *self {
///             CliError::Io(ref err) => write!(f, "IO error: {}", err),
///             CliError::Parse(ref err) => write!(f, "Parse error: {}", err),
///             CliError::NoneError(ref err) => write!(f, "Command args error: {:?}", err),
///         }
///     }
/// }
/// impl Error for CliError {
///     fn description(&self) -> &str {
///         match *self {
///             CliError::Io(ref err) => err.description(),
///             CliError::Parse(ref err) => Error::description(err),
///             CliError::NoneError(ref err) => "NoneError",
///         }
///     }
///     fn cause(&self) -> Option<&Error> {
///         match *self {
///             CliError::Io(ref err) => Some(err),
///             CliError::Parse(ref err) => Some(err),
///             _ => None,
///         }
///     }
/// }
///
/// impl From<io::Error> for CliError {
///     fn from(err: io::Error) -> CliError {
///         CliError::Io(err)
///     }
/// }
///
///
/// impl From<NoneError> for CliError {
///     fn from(err: NoneError) -> CliError {
///         CliError::NoneError(err)
///     }
/// }
///
/// impl From<num::ParseIntError> for CliError {
///     fn from(err: num::ParseIntError) -> CliError {
///         CliError::Parse(err)
///     }
/// }
///
/// fn run(filename: Option<String>) -> ParseResult<i32> {
///     let mut file = File::open(filename?)?;
///     let mut contents = String::new();
///     file.read_to_string(&mut contents)?;
///     let mut sum = 0;
///     for c in contents.lines(){
///         let n: i32 = c.parse::<i32>()?;
///         sum += n;
///     }
///     Ok(sum)
/// }
///
/// type ParseResult<i32> = Result<i32, CliError>;
///
/// fn main() {
///     let filename = env::args().nth(1);
///     match run(filename) {
///         Ok(n) => {
///             println!("{:?}", n);
///         },
///         Err(e) => {
///             eprintln!("main error: {}", e);
///             process::exit(1);
///         }
///     }
/// }
/// ```
pub fn error_handle(){
    unimplemented!();
}