`From<T>` defines a standard, infallible conversion from `T` into another type. Implement it on the destination type rather than writing a one-off conversion routine. An `Into` implementation then becomes available for the reverse calling style. section 4.7 section 4.7.2
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);
}
A wrapper implements `From<&str>` and constructs its inner `String` with `other.into()`. The caller can use `StringWrapper::from(...)` without spelling out a destination in a type argument. section 4.7
Error conversion is a common reason to implement `From`. If a function returns `Result<String, Error>` but `File::open` returns `std::io::Error`, `?` needs `From<std::io::Error> for Error` to return early with the function’s error type. The compiler reports the missing implementation when the types differ. section 4.6 section 4.7
impl From<std::io::Error> for Error {
fn from(other: std::io::Error) -> Self {
Self {
message: other.to_string(),
}
}
}
This implementation turns an I/O error into the crate’s message-bearing error type, allowing the file-reading function’s `?` expressions to compile. section 4.6
The same conversion can be explicit at a boundary: SQLx query methods returning `sqlx::Error` use `.map_err(Into::into)` to produce the application’s error type. Implement `From` for the conversion; use `Into::into` where `map_err` requires a conversion function. section 9.6.2
Practical checks:
- Prefer `From` over a custom conversion method when a standard type conversion fits. section 4.7.2
- When `?` cannot convert an error, check the function’s `Result` error type and implement the conversion the compiler identifies. section 4.7
- For Rust versions before 1.41, account for the stated restriction on implementing `From` when the destination is an external type. section 4.7



