4 ms·
Why cant every literal "abc" just be instantiated as a heap String by default? You could have a separate notation like &"abc" when you want a slice, similar to
by nikisweeting 6y ago
Why cant every literal "abc" just be instantiated as a heap String by default? You could have a separate notation like &"abc" when you want a slice, similar to python's b"abc" r"abc", etc. modifiers. Heap Strings seem much more useful in general.
- brundolf 6y agoIt would be pretty wasteful; in any read-only context you'll need a &str anyway, and making them all Strings would cause tons of unneeded allocations. Many Rust devs care a lot about avoiding unnecessary allocations: some people even use Rust on embedded systems that don't allow allocations at all, so building allocation into a language fundamental would likely be a mistake.
- nikisweeting 6y agoOk, I can see why it's not the default, but do you know why they didn't give it some syntax sugar to at least make it less painful/verbose to create one? let a = "abc" // this is a &str let b = s"abc" // this is a String
- estebank 6y agoThere have been conversations about this, but none that pushed forward an RFC that answered all the potential concerns. It is indeed a wart, one that I would personally like to see fixed, but I'm also ambivalent on whether I would like to make String nicer to use on literals or instead focus our efforts to make Cow<'_, str> a much nicer (and prevalent) type. https://internals.rust-lang.org/t/pre-rfc-custom-string-literals/5037 https://internals.rust-lang.org/t/pre-rfc-custom-string-lite... https://internals.rust-lang.org/t/pre-rfc-allowing-string-literals-to-be-either-static-str-or-string-similar-to-numeric-literals/5029 https://internals.rust-lang.org/t/pre-rfc-allowing-string-li... https://internals.rust-lang.org/t/pre-rfc-string-literals-through-prefixes/2928 https://internals.rust-lang.org/t/pre-rfc-string-literals-th...
- Daishiman 6y agoSystem programming languages avoid allocations and unnecessary resource consumption. I'd say it's one of their hallmark characteristics. The programming convenience of higher-level languages comes at a very substantial cost of requiring a complex runtime, more memory for data structures, unpredictable performance, and pushing complexity where it's not visible. One philosophy favors visibility over resources, the other favors convenience of use.
- scoutt 6y agoYou can be using a system that doesn't have a memory allocator (so no heap memory), like in many embedded systems.