Into is Rust’s standard-library trait for infallible conversion into a target type. It is reciprocal to From and is commonly used through .into(). section 4.7
Use Into with these practical rules:
- Implement From rather than Into whenever possible; the compiler derives the reciprocal Into implementation. section 4.7 section 4.7.2
- Call .into() when the destination type is already determined by context, such as constructing a wrapper from a borrowed string. section 4.7
- Use Into::into with map_err when converting database errors into an application error type. section 9.6.2
Converting errors with ?
A function returning Result<String, Error> cannot use ? on File::open or read_to_string until From<std::io::Error> for Error exists. Once that conversion is implemented, ? can convert the underlying I/O error automatically. section 4.7
struct StringWrapper(String);
impl From<&str> for StringWrapper {
fn from(other: &str) -> Self {
Self(other.into()) #1
}
}
fn main() {
println!("{}", StringWrapper::from("Hello, world!").0);
}
Inspect a focused implementation that converts &str into a StringWrapper and uses conversion inside the wrapper construction. section 4.7
