I’ve been following the discussion in https://users.rust-lang.org/t/ergonomics-of-creating-string-s/850 about the ergonomics of creating String objects.
Current Situation
The current situation is that there are a few main ways to create String instances:
"foobar".to_string()
"foobar".to_owned()
"foobar".into()
…and some others by using constructors. Of these the last version probably has the best performance, but might need type annotations in some situations. .to_string() is the most obvious / easy to remember approach, but it invokes the formatting machinery and offers less performance. (Also, it’s not meant for creating String instances from 'static strings, which is confusing to newbies. OTOH it’s the way shown in most of the book and the tutorials.)
Another way to solve the issue is to create interfaces that take T: Into<String> as parameters, but that quickly results in hard to read interfaces, as Strings are usually used all over the place.
Proposal
Why not introduce a prefix to create String literals? In order to match byte literal syntax (b"foobar") a s"foobar" (for string) or a u"foobar" (for unicode, like in Python) prefix could be used.
Downsides
- It would probably hide the cost of allocating a new
String.
- The byte literal creates a static reference, while the string literal would create a non-static owned object. (see also)
- Newer code using the literals would probably be incompatible with previous Rust versions.
I would be happy about any comments
Maybe it’s a terrible idea (I only started doing Rust in January, so I don’t know much about the internals), but I hope the current situation can be improved somehow.