Hacker News new | past | comments | ask | show | jobs | submit login

> 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.




I guess this works like the Javascript `const` keyword.


Java 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.


And 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.


In 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


Java has final, which I frequently find has junior dev advocates who believe it avoids changes that it doesn’t.


Afaik 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.


Only through an escape hatch (a big red flag one at that). You aren't supposed to.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: