3 ms·
An example of a constant would be a literal, such as "Hello, World!" or 4 or false You can see that not only can't you change these values, it doesn't even mea
by tialaramex 3y ago
An example of a constant would be a literal, such as "Hello, World!" or 4 or false
You can see that not only can't you change these values, it doesn't even mean anything to speak about doing so, they're not variables which have values, they're the values themselves.
Whereas an example of an immutable variable would be the std::vector we're being asked to check the length of in a call to size() - this certainly is a variable, somebody else can change it, but we must not.
If we name a constant in Rust like { const TIMEOUT: u32 = 1234; }, we're not saying we want a variable with this name TIMEOUT and then we mustn't change it - instead we are giving a name to this arbitrary constant TIMEOUT (and it has to be constant, Rust won't let us make constants unless they actually are) and then any time we say that name, we get the same value, not the same variable, there is no variable, the same value, the constant one, as if we'd written it here.
So for example the C++ trick where you "cast away" the const-ness doesn't make any sense in Rust because those aren't immutable variables, we can't even try to make them mutable, they're not variables. It's not Undefined Behaviour, it's gibberish, even C++ won't let you write false = true; for example, that's just clearly nonsense.
- soulbadguy 3y ago> An example of a constant would be a literal, such as "Hello, World!" or 4 or false Not quite, those are literals values. As mentioned in the C++ standards, const-ness is a quality of variables... Not of values.
- teo_zero 3y agoBut that's exactly the criticism: that C++ used the word const for something different from its theoretical meaning, something that could have been better expressed with the word immutable.