TM90
TM90

Reputation: 700

to_string with generic argument

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

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

But this will obviously not work because to_string is not implemented for the type T.

So my question is how would I check for the type of the argument and then apply to_string if needed and how can I tell the compiler that I now know that the variable is a defined type?

Upvotes: 5

Views: 3858

Answers (1)

squiguy
squiguy

Reputation: 33380

You can tell the compiler that T must implement the ToString trait like this:

use std::string::ToString;

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

Upvotes: 3

Related Questions