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:
- How do I import the
to_stringmethod forstrdirectly? - Why does
std::str::to_stringnot work given thatstr::to_stringis in the namespace? - In general, is there a way to invoke trait methods on an object using
trait_method(obj)syntax instead ofobj.trait_method()syntax?
>Solution :
-
You cannot.
-
Because:
a) It is not;
ToStringis implemented on the typestr, andstd::stris a separate module defined instd(sostr::to_stringif anything, withoutstd).b) You cannot import trait methods.
-
Not without specifying the trait (
Trait::trait_method(obj)).