Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are immutable structs default in Julia?

Tags:

julia

I noticed that when a struct is declared, its fields are immutable by default unless the mutable keyword is used.

What is the reason for this? Is it good practice to use mutable structs?

like image 629
Jason Barnett Avatar asked Jan 14 '20 16:01

Jason Barnett


People also ask

Should structs be immutable?

A struct type is not immutable. Yes, strings are. Making your own type immutable is easy, simply don't provide a default constructor, make all fields private and define no methods or properties that change a field value. Have a method that should mutate the object return a new object instead.

What does it mean that structs are immutable?

That means every variable is considered a copy, and its members are isolated from changes made to other variables. Structs are not copied on mutation.


1 Answers

This is discussed in this PR to Julia. I'll just quote from Jeff Bezanson:

  • We should steer people to immutable types by default. Immutable is generally better and faster, has better default behavior with ===, and it's really pretty rare to need to update object fields. Base has many more immutable types than mutable, and in making this change it seemed to me that even more types could be made immutable. But type Foo looks more natural than immutable Foo, so type tends to be the default choice. This change reverses that, with struct Foo being more natural, and immutable. Writing mutable struct Foo makes you ask "does this really need to be mutable?", which is a good thing!
  • Immutable struct types are the closest thing we have to value type structs in other languages. We inline them in arrays in at least some cases, and being immutable makes it much harder to tell whether they are value or reference types.
  • FWIW, Rust also uses struct and makes them immutable. Not that we need to copy Rust, but it adds confidence that this is a reasonable thing to do.

In short, immutable types are more performant, because they can be stack allocated and the compiler can reason better about them. They are also easier for humans to reason about, since they can't change from under you.

like image 117
Jakob Nissen Avatar answered Oct 13 '22 00:10

Jakob Nissen