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_string
method forstr
directly? - Why does
std::str::to_string
not work given thatstr::to_string
is 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;
ToString
is implemented on the typestr
, andstd::str
is a separate module defined instd
(sostr::to_string
if anything, withoutstd
).b) You cannot import trait methods.
-
Not without specifying the trait (
Trait::trait_method(obj)
).