The From and Into traits are standard Rust traits that define how to convert between different types, with From implementing the conversion logic and Into automatically delegating to From.
use std::str::FromStr;
fn main() {
// From: Convert String to &str (explicit implementation)
let s: String = "hello".to_string();
let slice: &str = s.as_str(); // Uses Into implicitly
// Into: Convert &str to String (auto-implemented if From exists)
let s2: String = "world".into();
// Custom example: Convert u32 to MyType
struct MyType(u32);
impl From<u32> for MyType {
fn from(val: u32) -> Self {
MyType(val)
}
}
let my_val: MyType = 42.into(); // Works because From<u32> is implemented
}