5 ms·
> Objects, list and maps variables are only reference to them. Meaning you can't assign a new list to a constant variable but you can modify the list itself. I
by lelanthran 3y ago
> Objects, list and maps variables are only reference to them. Meaning you can't assign a new list to a constant variable but you can modify the list itself.
In what contexts is this useful? I know it matches some other languages view of `constant`, but I feel that this sort of behaviour is very surprising to a user.
Assuming the following code:
object Person {
str name = "Joe", | Fields can have default values
int age = 35,
}
const me = Person{...}
const [int] list = [4, 5, 6]
In what contexts is it useful to allow the name of `me` to be changed, or the length of the list to be changed, while disallowing the variable to reference a different underlying object?
Wouldn't the expectation of a programmer be the other way around? IOW, a symbol that is declared as constant can be a reference to any constant object, so the programmer can always assign that symbol to another constant object, but the objects themselves should not be mutable.
- hannofcart 3y agoI guess this works like the Javascript `const` keyword.
- pkulak 3y agoJava too. Rust is the only language I’ve used where “immutable” means everything through the whole reference tree is also immutable. Well, only language that allows mutation at all.
- IshKebab 3y agoAnd C/C++. Probably other value based languages like Go and Zig. JavaScript probably behaves like that because `const` was tacked on (and it's dynamically typed so there's no place to mark parameters as const). There is Object.freeze() which sort of makes something immutable, but it's not really the same. Java doesn't even have const so I guess they just didn't care about const correctness or didn't have time to add it.
- cowsandmilk 3y agoJava has final, which I frequently find has junior dev advocates who believe it avoids changes that it doesn’t.
- throwaway143829 3y agoIn Go, consts can only be used for primitives like 42, "foo" etc. - not structs, because the language doesn't have a concept of immutability (and so wouldn't be able to enforce const-ness) except for primitives. More info here: https://go.dev/blog/constants https://go.dev/blog/constants
- skitter 3y agoAfaik for C & C++, that's not true – you can turn const references into normal references and are even allowed to mutate the object they point to unless said object is declared as const.
- IshKebab 3y agoOnly through an escape hatch (a big red flag one at that). You aren't supposed to.
- deleted 3y ago[deleted]