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

Convert - แปลงชนิดข้อมูล

std::convert มี traits สำหรับแปลงระหว่าง types อย่างปลอดภัย!

Traitใช้ทำอะไรอาจ fail?
Fromแปลงจาก type อื่นNo
Intoแปลงไป type อื่นNo
TryFromแปลงจาก (อาจ fail)Yes
TryIntoแปลงไป (อาจ fail)Yes
AsRefยืมเป็น referenceNo
AsMutยืมเป็น mutable refNo
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 เพื่อปลดล็อกบทความทั้งหมด