naufraghi
naufraghi

Reputation: 1552

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

Why does this function call:

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);
}

raise this compilation error:

<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

I know that the code is broken as OsString does not implement ToString.

Upvotes: 0

Views: 577

Answers (1)

huon
huon

Reputation: 102166

The trait ToString is implemented by all types that implement Display (and, in fact, only those types):

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

So, when the compiler looks for an implementation of ToString, it ends up trying to look for one for Display and that's where the trait search fails for OsString (Display doesn't have the same sort of "blanket impl").

Upvotes: 2

Related Questions