unwrap_or_else(|error| { panic!("Problem creating the file: {:?}", error); }) } else { panic!("Problem opening the file: {:?}", error); } }); } 失败时 panic 的简写:unwrap 和 expect 如果Result值是成员Ok,unwrap会返回Ok中的值。如果Result是成员Err,unwrap会为我们调用panic!。
unwrap_or_else(|error| { if error.kind() == ErrorKind::NotFound { File::create("hello.txt").unwrap_or_else(|error| { panic!("Problem creating the file: {:?}", error); }) } else { panic!("Problem opening the file: {:?}", error); } }); } ...
本文简要介绍rust语言中 core::result::Result.unwrap_or_else 的用法。用法pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T 返回包含的 Ok 值或从闭包计算它。例子基本用法:fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert...
本文简要介绍rust语言中 std::option::Option.unwrap_or_else 的用法。 用法 pub fn unwrap_or_else<F>(self, f: F) -> T where F: FnOnce() -> T, 返回包含的 Some 值或从闭包计算它。 例子 let k = 10; assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); assert_eq!(None.unwrap...
(1) unwrap() 在Rust 中,unwrap() 方法用于从 Result 类型中提取成功时的返回值。如果 Result 类型的值是 Ok(表示成功),则 unwrap() 方法将返回 T;如果 Result 类型的值是 Err(表示失败),则 unwrap() 方法将触发一个 panic,抛出一个 E 类型的错误。如果您在调用 unwrap() 方法时遇到错误,说明您正在处...
unwrap_or("100"); 或者您可以将其放入函数中并使用 ?。 fn read_content_length(resp: &reqwest::Response) -> Option<&str> { resp.headers() .get(reqwest::header::CONTENT_LENGTH)? .to_str() .ok() } let resp_headers: &str = read_content_length(&resp).unwrap_or("100"); 但是...
ErrorKind::NotFound => File::create("hello.tx").unwrap_or_else(|error| {panic!("Problem creating the file: {:?}", error); }),// 匹配错误原因, 对于文件不存在的错误处理为创建文件other_error_kind =>panic!("Problem opening the file: {:?}", other_error_kind) ...
处理match复杂时,我们可以通过unwrap_or_else方法处理错误,简化match嵌套表达式。 panic简写:unwrap 和 expect unwrap 作用 unwrap在处理Result<T, E> 时,若返回为Ok,则unwrap会返回Ok的值,若为Err,则unwrap会调用panic!宏。 缺点: 对Result<T, E>处理,如果在多处使用 unwrap,则需要花更多的时间来分析到底是哪...
usestd::fs::File;usestd::io::ErrorKind;fnmain(){letgreeting_file=File::open("hello.txt").unwrap_or_else(|error|{iferror.kind()==ErrorKind::NotFound{File::create("hello.txt").unwrap_or_else(|error|{panic!("Problem creating the file: {:?}",error);})}else{panic!("Problem openi...
File::create("test.txt").unwrap_or_else(|error| { panic!("err create file: {:?}", error); }) }else{ panic!("Err open file: {:?}", error); } }); } unwrap方法 unwrap:match表达式的一个快捷方法。 若Result结果是OK,返回Ok里面的值 ...