macro_rules! s { ($s:literal) => { ... }; ($s:expr) => { ... }; () => { ... }; }
Expand description
Converts a str
string literal to an owned String
.
This macro provides syntactic sugar to convert static str
instances to
String
s - this saves having to do "foo".to_owned()
or
String::from("foo")
.
It will also convert any other type that implements the ToString
trait
to a String
— providing that it is passed in as a variable or some kind
of expression, and not as a literal. That’s because, at present, there is no
way for the macro to tell the difference between str
literals and other
literals such as numbers, and as a result it will call to_owned()
on them
and give a non-String
result, which will not match expectations. For
this reason, this ability is not as useful as the str
behaviour, and it
does not provide a consistent interface for converting to String
s (and
nor is it intended to).
When converting from other types it is likely best to use the standard
conversion functions directly, to avoid confusion, and so the recommendation
is to only use this macro as shorthand for converting str
instances.
The inspiration for this macro comes from the velcro
crate, which provides a range of macros for creating collections, building
on the built-in vec!
macro.
§Examples
use rubedo::sugar::s;
assert_eq!(s!("foo"), "foo");
assert_eq!(s!("foo"), "foo".to_owned());
assert_eq!(s!("foo"), "foo".to_string());
assert_eq!(s!("foo"), String::from("foo"));