4 ms·
The trick is that an empty string doesn’t actually own any data on the heap. It’s basically a null pointer, and all string methods check for that in some way. T
by codeflo 5y ago
The trick is that an empty string doesn’t actually own any data on the heap. It’s basically a null pointer, and all string methods check for that in some way. This is a typical optimization trick that many languages implement (empty lists and strings are very common). Defining new to be const just makes this optimization a requirement.
- brundolf 5y agoBut still- at a language semantics level, values can't have multiple owners, and String couldn't implement Copy just for this one case. So how does this reconcile with the borrow-checker? Or can consts have multiple owners since they're immutable and have a static lifetime? Is this just the first case of a non-Copy being const, so the question has never come up before?
- codeflo 5y agoAh, I get your question now, I thought you were talking about const functions. Well, const values in Rust are funny things, they're not linked into the executable, they don't have an address or a lifetime. That confused me too for a while. They're purely a shortcut for a value expression, not that different from a #define in C. Statics, in contrast, have a storage location and a static lifetime. Compare: const CONST_STRING: String = String::new(); static STATIC_STRING: String = String::new(); fn main() { let x: String = CONST_STRING; // fine let y: String = STATIC_STRING; // error: cannot move out of static item }
- brundolf 5y agoOh. I think I didn't realize both existed; I'd only used statics before (and knew about const functions), but didn't know about const expressions.