Live data from Hacker News

John Carmack on mutable variables

twitter.com

91–100 of 663 posts

Re: John Carmack on mutable variables

#97
post #4

Years ago I did a project where we followed a lot of strict immutability for thread safety reasons. (Immutable objects can be read safely from multiple threads.) It made the code easier to read because it was easier to track down what could change and what couldn't. I'm now a huge fan of the concept.

You should check out Rust

Re: John Carmack on mutable variables

#99

Earlier quoted context omitted.

There’s no mutating happening here, for example: if cond: X = “yes” else: X = “no” X is only ever assigned once, it’s actually still purely functional. And in Rust or Lisp or other expression languages, you can do stuff like this: let X = if cond { “yes” } else { “no” }; That’s a lot nicer than a trinary operator!

Swift does let you declare an immutable variable without assigning a value to it immediately. As long as you assign a value to that variable once and only once on every code path before the variable is read: let x: Int if cond { x = 1 } else { x = 2 } // read x here

Same with Java and final variables, which should be the default as Carmack said. It’s even a compile time error if you miss an assignment on a path.

Re: John Carmack on mutable variables

#100
post #7

Earlier quoted context omitted.

> If you want a language where const is the default and mutable is a keyword, try F# for starters. I switched and never looked back. 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…

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.
Post reply on HN