To_string with a common argument

I have the following generic function and now want to convert any type, if possible, to a string.

fn write_row<T>(row: T) {
    let s: String = row.to_string();
}

      

But that obviously won't work because to_string is not implemented for type T.

So my question is how do I check the type of the argument and then apply to_string if needed, and how do I tell the compiler that I now know the variable is of a certain type?

+3


source to share


1 answer


You can tell the compiler T

to implement the property ToString

like this:



use std::string::ToString;

fn write_row<T: ToString>(row: T) {
    let s: String = row.to_string();
}

      

+2


source







All Articles