Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading