From and Into
Types implement From and Into to facilitate type conversions. Unlike as, these traits correspond to lossless, infallible conversions.
fn main() { let s = String::from("hello"); let addr = std::net::Ipv4Addr::from([127, 0, 0, 1]); let one = i16::from(true); let bigger = i32::from(123_i16); println!("{s}, {addr}, {one}, {bigger}"); }
Into بهطور خودکار زمانی پیادهسازی میشود که From پیادهسازی شده باشد:
fn main() { let s: String = "hello".into(); let addr: std::net::Ipv4Addr = [127, 0, 0, 1].into(); let one: i16 = true.into(); let bigger: i32 = 123_i16.into(); println!("{s}, {addr}, {one}, {bigger}"); }
This slide should take about 5 minutes.
- به همین دلیل معمولاً تنها
Fromپیادهسازی میشود، زیرا تایپ شما بهطور خودکار پیادهسازیIntoرا نیز دریافت میکند. - هنگام اعلام تایپ ورودی تابعی مانند “هر چیزی که میتواند به یک
Stringتبدیل شود”، قاعده برعکس است، باید ازIntoاستفاده کنید. تابع شما تایپهای را قبول میکند که پیادهسازیFromدارند و همچنین تایدهایی که فقطIntoرا پیادهسازی کردهاند.