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

Conversion Traits

From, Into, TryFrom, TryInto และ conversion patterns

fn main() {
// From - explicit conversion
let s: String = String::from("hello");
let num: i64 = i64::from(42i32);
println!("String: {}", s);
println!("i64: {}", num);
// Into - reverse of From (auto-generated)
let s: String = "hello".into();
let num: i64 = 42i32.into();
println!("Into String: {}", s);
println!("Into i64: {}", num);
// Generic functions with Into
fn accepts_string<S: Into<String>>(s: S) {
let string = s.into();
println!("Got: {}", string);
}
accepts_string("literal"); // &str
accepts_string(String::from("owned")); // String
accepts_string('X'); // char
// Multiple conversions
let v: Vec<u8> = b"hello".to_vec();
let s: String = String::from_utf8(v).unwrap();
println!("From bytes: {}", s);
}

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

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