症状
即便方法确实存在于标准库或某个 crate 中,仍出现 error[E0599]: no method named ... found for type ...。通常在为某个 trait 加上 use 之后就会消失。
诊断
确认定义方法的 trait 与接收者:
use std::io::Read; // brings read_to_string into scope for readers
fn load(mut reader: impl Read) -> String {
let mut s = String::new();
reader.read_to_string(&mut s).unwrap(); // needs Read in scope
s
}
用 cargo doc 查看该方法属于哪个 trait。
修复
导入该 trait、启用相应 feature,或调整接收者类型:
use std::io::Read; // trait method
let bytes = opt.as_ref(); // adjust receiver type
验证
cargo check 通过,方法可被找到,整个 crate 不再出现 E0599。