Convert - แปลงชนิดข้อมูล
std::convert มี traits สำหรับแปลงระหว่าง types อย่างปลอดภัย!
convert มีอะไร?
Section titled “convert มีอะไร?”| Trait | ใช้ทำอะไร | อาจ fail? |
|---|---|---|
From | แปลงจาก type อื่น | No |
Into | แปลงไป type อื่น | No |
TryFrom | แปลงจาก (อาจ fail) | Yes |
TryInto | แปลงไป (อาจ fail) | Yes |
AsRef | ยืมเป็น reference | No |
AsMut | ยืมเป็น mutable ref | No |
fn main() { // ============================================ // Convert basics // ============================================
// From: String::from(&str) let s = String::from("hello");
// Into: let s: String = "hello".into() let s2: String = "hello".into();
// TryFrom: may fail let n: Result<u8, _> = 300i32.try_into(); println!("300 -> u8: {:?}", n); // Error
let n: Result<u8, _> = 100i32.try_into(); println!("100 -> u8: {:?}", n); // Ok(100)}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google