Why does the `ToString` trait exist?

Why was the to_string() method not simply added to the Display trait?

1 Like

Sadly, it's more like a historical accident but we can't remove it due to the backward compatibility.

Mostly because Display is in core, and String is in alloc, so Display cannot reference String

15 Likes

The deeper reason is that Display is polymorphic. Dumping to a String is one implementation, but Display also works with non-allocating output objects.

1 Like

Polymorphic Display does not prevent one from adding a fn to_string(&self) -> String { ... } default implementation. The fact that String is in another crate does.

6 Likes