Refs and Software Transactional Memory

Most objects in Clojure are immutable. When you really want mutable data, you must be explicit about it, such as by creating a mutable reference (ref) to an immutable object. You create a ref with this:

 ​(​ref​ initial-state)​

For example, you could create a reference to the current song in your music playlist:

 ​(def current-track (ref "Mars, the Bringer of War"))​
 ​-> #'user/current-track​

The ref wraps and protects access to its internal state. To read the contents of the reference, you can call deref:

 ​(​deref​ reference)​

The deref function can be shortened to the @ reader macro. Try using both deref and @ to dereference current-track:

 ​(deref current-track)​
 ​-> "Mars, the Bringer of War"​

Get Programming Clojure, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.