Hacker News new | ask | show | jobs
by saghm 68 days ago
That's a fair point, and maybe even a case that there should be more keywords rather than fewer.

Relatedly, I still sometimes get tripped up by the nuances of using `const` versus `static` for top-level constants. Most of the time the difference is entirely opaque to the programmer (because it's not obvious when most things are getting inlined or being referenced from a single place in memory), but it's possible to run into cases where one works and the other won't (e.g. trying to be clever with `OnceCell` rather than `OnceLock`).

1 comments

It might help to think about whether you want an actual singular concrete thing, which means you need static or whether you just want to talk about the idea and so it doesn't matter whether at runtime this exists many places or nowhere at all, which is a const.

Statics can be mutated - though not safely - because they are a single concrete thing so they can be changed, whereas it can't mean anything to mutate a constant, hence the word "constant".

For larger objects you might want a single concrete thing even though it might intuitively not seem important because it impacts performance. For example if we keep talking about FACTOR[n] where FACTOR is an array of a million numbers (maybe computed by scientist colleagues for your application) and n is a variable, if FACTOR is const Rust is going to just put a copy of that enormous array everywhere it needed to do this indexing operation, which gets out of hand really fast, whereas if we use static we get a single concrete thing, named FACTOR and everywhere in the program will use that one single million number array, much tidier and less likely to result in say, running out of RAM on a small computer.

Yeah, the problem is that I usually think about stuff like this up front and then select something, and when much later I happen to change something, I focus so much on the types and the values that I forget that I need to also look at the keyword itself.

For what it's worth, my rule of thumb is usually to start with `static` and then only swap to `const` if I have a reason to. If I recall correctly, the issue I alluded to above was around picking between `LazyCell` and `LazyLock` and swapping between `&Path` and `PathBuf`, and some combination of them only working with `const` and not `static`.