为什么这个函数会调用:
use std::string::ToString;
use std::ffi::OsString;
fn len<T: ToString>(v: &T) -> usize {
v.to_string().len()
}
fn main() {
let text = OsString::from("Hello, world!");
let tlen = len(&text);
println!("len('{:?}') = {}", &text, tlen);
}
引发此编译错误:
<anon>:10:16: 10:19 error: the trait `core::fmt::Display` is not implemented for the type `std::ffi::os_str::OsString` [E0277]
<anon>:10 let tlen = len(&text);
^~~
<anon>:10:16: 10:19 note: `std::ffi::os_str::OsString` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
<anon>:10 let tlen = len(&text);
^~~
error: aborting due to previous error
playpen: application terminated with error code 101
我知道代码已损坏,因为OsString
未实现ToString
。
答案 0 :(得分:2)
trait ToString
是implemented by all types that implement Display
(事实上,只有那些类型):
impl<T: fmt::Display + ?Sized> ToString for T {
...
因此,当编译器查找ToString
的实现时,它最终会尝试为Display
寻找一个,OsString
({1}}的特征搜索失败的地方没有相同类型的“毯子冲击”)。