将OsString传递给func <t:tostring =“”>的误导性错误,显示特征来自何处?

时间:2015-04-29 12:53:58

标签: compiler-errors rust traits

为什么这个函数会调用:

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

1 个答案:

答案 0 :(得分:2)

trait ToStringimplemented by all types that implement Display(事实上,只有那些类型):

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

因此,当编译器查找ToString的实现时,它最终会尝试为Display寻找一个,OsString({1}}的特征搜索失败的地方没有相同类型的“毯子冲击”)。