title | description | canonical |
---|---|---|
Mutation | Imperative and mutative programming capabilities in ReScript | /docs/manual/v11.0.0/mutation |
ReScript has great traditional imperative & mutative programming capabilities. You should use these features sparingly, but sometimes they allow your code to be more performant and written in a more familiar pattern.
Let-bindings are immutable, but you can wrap it with a ref
, exposed as a record with a single mutable field in the standard library:
<CodeTab labels={["ReScript", "JS Output"]}>
letmyValue=ref(5)
varmyValue={contents: 5};
You can get the actual value of a ref
box through accessing its contents
field:
<CodeTab labels={["ReScript", "JS Output"]}>
letfive=myValue.contents// 5
varfive=myValue.contents;
Assign a new value to myValue
like so:
<CodeTab labels={["ReScript", "JS Output"]}>
myValue.contents=6
myValue.contents=6;
We provide a syntax sugar for this:
<CodeTab labels={["ReScript", "JS Output"]}>
myValue:=6
myValue.contents=6;
Note that the previous binding five
stays 5
, since it got the underlying item on the ref
box, not the ref
itself.
Note: you might see in the JS output tabs above that ref
allocates an object. Worry not; local, non-exported ref
s allocations are optimized away.
Before reaching for ref
, know that you can achieve lightweight, local "mutations" through overriding let bindings.