将 OsString 传递给 func<T: ToString> 的误导性错误,Display 特征从何而来?

Misleading error passing OsString to a func<T: ToString>, where does Display trait comes from?

为什么调用这个函数:

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

trait ToString is implemented by all types that implement Display(实际上只有那些类型):

impl<T: fmt::Display + ?Sized> ToString for T {
    ...

因此,当编译器查找 ToString 的实现时,它最终会尝试为 Display 查找一个实现,而这正是 OsString 的特征搜索失败的地方(Display 没有相同类型的 "blanket impl").