src/std-traits/from-and-into.md
From and IntoTypes implement From and Into to facilitate type conversions.
Unlike as, these traits correspond to lossless, infallible conversions.
# // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
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 is automatically implemented when From is implemented:
# // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
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}");
}
From, as your type will get Into
implementation too.String", the rule is opposite, you should use Into. Your
function will accept types that implement From and those that only
implement Into.