Can we have a proposal for ref syntax?

let x = ref(...) is bad and the .contents syntax is horrendous. it’s confusing and makes no sense to someone who doesn’t understand the internals of how js deals with references and in-memory storage mutability. worse off, it actually exposes this implementation detail.

why is it called ref? because it’s a reference, but that only makes sense if you understand the js implementation, i.e., ref sort of implies mutability in js (for non-frozen objects). why isn’t it let x = mut(...) or even mut x = ...?

also, using .contents is terribly ugly. why is it called contents of what? the ref? but i only want a mutable value.

i can live with let x = ref(...) but just as we have := for ref assignment (which should be changed too, tbh), we should have something for reading the contents, for example ^:

let x = ref(None)
// or: let x = mut(None)
// or: mut let x = None

x := Some(42)
// or to unify set and get: x^ = Some(42)

let y = x // binds to point to the same ref
let z = x^ // binds to the value contained in the ref

give me your thoughts on this, maybe you have better ideas, i just feel refs are a wart in the language right now.

1 Like

The naming and pattern comes from ML languages like Ocaml.

https://cs3110.github.io/textbook/chapters/mut/refs.html

This is also how the useRef hook in react works.

I don’t mind the way it currently is, but I do see how a style more like mut from Rust could be interesting.

Personally I don’t think it’s worth changing a language feature that is inspired by language A to a language feature inspired by language B. The only reason that I think this would be worth it is if we’re adopting or changing syntax to align with JavaScript.

Since the ref exists in React, which is very common and has widespread usage, and we don’t have a native JS alternative, I would be in favor of leaving it as is and perhaps enhancing the documentation.

2 Likes