Re:John Carmack on Mutable Variables
by bathtub365 on Friday October 31, 2025 @01:25AM
(#45768692)
Are there languages that automatically extend this to things like data structure members? One of the things I like about the C++ const keyword is that if you declare an instance of a struct/class as const it extends that to its members. If the instance isn’t const, you can still mutate them (as long as they aren’t declared const within the structure itself)
Rust works this way, yes. There are escape hatches though, which allow interior mutability.
Yeah, here's an example: https://play.rust-lang.org/?version=stable&mode=debug&editio...
Re:John Carmack on Mutable Variables
by umanwizard on Friday October 31, 2025 @04:23AM
(#45769534)
If I understand what you’re asking correctly, rust is also like this. If you have a non-mut value of (or non-mut reference to) an object, you only get non-mut access to its members.
Re:John Carmack on Mutable Variables
by Fire-Dragon-DoL on Friday October 31, 2025 @03:18AM
(#45769193)
In typescript and js you get immutable references, but the data is mutable. Definitely not the same thing
You have `as const`. Yes I know it's not enforced at runtime, but the type system does support it.
There’s Object.freeze for enforcing at runtime.
In Java you can use final[1]. And yes, if final points to an ArrayList you can change it, but you can also use final together with immutable data structures[2].
Did you know that "final" does not actually mean final in Java (as in: the variable can be constant folded)? Reasons include reflection and serialization (the feature that nowadays nobody uses, but due to backwards compatibility the Java language developers always have to worry about?). There was an excellent talk about this recently, I think triggered by a new JEP "stable values": https://youtu.be/FLXaRJaWlu4
That is interesting, but I am already aware of it.
For anyone who wonder about why, it is meant to help us as programmers avoid shooting ourselves in the feet, not as some kind of unbreakable enforcement.
Rust is also like this (let x = 5; / let mut x = 5;).
Or you can also use javascript, typescript and zig like this. Just default to declaring variables with const instead of let / var.
Or swift, which has let (const) vs var (mutable).
FP got there first, but you don't need to use F# to have variables default to constants. Just use almost any language newer than C++.