Skip to content
เข้าสู่ระบบ

Convert Enums

Enums สำหรับ conversion operations

use std::convert::Infallible;
fn main() {
// Infallible - empty enum, can never be constructed
// Used as error type for infallible operations
fn always_succeeds() -> Result<i32, Infallible> {
Ok(42)
}
// Can safely unwrap - error is impossible
let value = always_succeeds().unwrap();
println!("Value: {}", value);
// Match - Err branch is unreachable
match always_succeeds() {
Ok(v) => println!("Got: {}", v),
Err(e) => match e {}, // Compile-time proof of unreachability
}
// From<Infallible> is implemented for any type
fn convert_result<E: From<Infallible>>() -> Result<i32, E> {
let result: Result<i32, Infallible> = Ok(100);
result.map_err(From::from)
}
let _: Result<i32, String> = convert_result();
// Size is 0 (empty enum)
println!("Size of Infallible: {}", std::mem::size_of::<Infallible>());
// Never type (!) is similar but unstable
// Infallible is stable equivalent for error types
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด