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:
to_string
method for str
directly?std::str::to_string
not work given that str::to_string
is in the namespace?trait_method(obj)
syntax instead of obj.trait_method()
syntax?You cannot.
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.
Not without specifying the trait (Trait::trait_method(obj)
).