How can I import `str::to_string` in Rust? (And is it possible to do this with trait methods in general?)

I want to turn a &str into a String which can be done simply with the method

let res = "my_string".to_string()

I prefer thinking of methods as acting directly on a structure so I’d like to write

let res = to_string("my_string").

The closest I’ve come to this so far is: str::to_string("my_string") but providing the namespace seems a bit verbose an unnecessary so I want to import the function into my namespace but I haven’t found a way to do it that doesn’t make the the compiler complain.

I thought that use std::str::to_string; would do the trick but the compiler says "no to_string in str".

I checked the source for str::to_string and realized that it appears to be the implementation of a trait but this is illegal use std::string::ToString::to_string; which makes sense because you wouldn’t be able to differentiate between which struct implemented the trait.

So this brings me to my closely related questions:

  1. How do I import the to_string method for str directly?
  2. Why does std::str::to_string not work given that str::to_string is in the namespace?
  3. In general, is there a way to invoke trait methods on an object using trait_method(obj) syntax instead of obj.trait_method() syntax?

>Solution :

  1. You cannot.

  2. Because:

    a) It is not; ToString is implemented on the type str, and std::str is a separate module defined in std (so str::to_string if anything, without std).

    b) You cannot import trait methods.

  3. Not without specifying the trait (Trait::trait_method(obj)).

Leave a Reply