【Rust】結果列舉(二)
阿新 • • 發佈:2022-05-28
環境
- Time 2022-03-25
- Rust 1.59.0
示例
as_deref
fn main() {
let result: Result<String, u32> = Ok("ok".to_owned());
let result: Result<&str, &u32> = result.as_deref();
println!("{:?}", result);
}
iter
fn main() { let result: Result<&str, u32> = Ok("ok"); println!("{:?}", result.iter().next()); }
expect
fn main() {
let result: Result<&str, u32> = Ok("ok");
println!("{:?}", result.expect("錯誤"));
}
unwrap
fn main() {
let result: Result<&str, u32> = Ok("ok");
println!("{:?}", result.unwrap());
}
unwrap_or_default
fn main() { let result: Result<&str, u32> = Err(44); println!("{:?}", result.unwrap_or_default()); }
expect_err
fn main() {
let result: Result<&str, u32> = Err(44);
println!("{:?}", result.expect_err("OK"));
}
unwrap_err
fn main() {
let result: Result<&str, u32> = Err(44);
println!("{:?}", result.unwrap_err());
}
and
fn main() { let result: Result<u32, u32> = Ok(44); println!("{:?}", result.and(Ok(4))); }
and_then
fn main() {
let result: Result<u32, u32> = Ok(44);
let result: Result<u32, u32> = result.and_then(|e| Err(e * 2));
println!("{:?}", result);
}
總結
瞭解了結果列舉中相關的一些方法。