直接回答:From 定义“如何从 T 构造出 Self”,Into 是它的互逆方向。标准库用一条 blanket impl 保证:实现了 From<T> 就自动获得 Into<T>,因此约定是只实现 From,手写 Into 既重复又可能与自动实现不一致。
展开解析:? 传播错误时隐式调用 From::from 做错误类型提升——给自定义错误枚举写好若干 From 实现,函数里就能用 ? 混用多种错误源。参数写成 impl Into<String> 可同时接受 &str 与 String。可能失败的转换用 TryFrom(返回 Result);数值窄化必须显式 as 或 TryFrom,as 是截断式转换、溢出不做检查,要谨慎。
fn save(name: impl Into<String>) { let s: String = name.into(); }
save("a.txt"); // 传 &str 也行,靠 From<&str> for String
impl From<io::Error> for AppError {
fn from(e: io::Error) -> Self { AppError::Io(e) }
}
追问方向:为什么不实现 Into 而实现 From?as 与 From 的语义差异?TryFrom 的 Error 类型如何设计?
(约 510 字)