To Rust or Not
Nov 6, 2017
2 minute read

Recently I’ve decided to revive an old game engine project but currently I’m at a crossroad, choosing a programming language: Kotlin or Rust. I mostly work with the JVM and have been using Kotlin on my personal projects for awhile now, so naturally it was my first choice. However, Rust have a compelling feature that I really want: “true” immutable data.

Kotlin’s val only guarantee reference immutability - it only prevents re-assignment, if the referenced type is mutable then you’re on your own.

data class Point(var x: Double, var y: Double)

val point = Point(1.0, 1.0)

// nope
point = Point(2.0, 3.0)

// totally fine
point.x = 3.0
point.y = 5.0

Rust on the otherhand has bind time mutability, a field is mutable or not depends at bind time.

struct Point {
    x: f64,
    y: f64

let point = Point { x: 1.0, y: 2.0 };

// nope
point = Point { x: 2.0, y: 3.0 };

// nope
point.x = 2.0;
point.y = 3.0;

If you want mutability use let mut instead of let.

let mut point = Point { x: 1.0, y: 2.0 };

// works now
point = Point { x: 2.0, y: 3.0 };

// this too
point.x = 2.0;
point.y = 3.0;

Rust also has interior mutability, but is beyond the scope of this post.

So, why do I want it? One of the design goals for my game engine is concurrency, having true immutable data helps prevent data races. Working with unsynchronized data can be catastrophic, especially with physics simulation and rendering.


True immutable data is very compelling feature and Rust is a really interesting language, however Kotlin’s ecosystem and the homecourt advantage are not worth letting go. Plus, true immutable data is one of Kotlin’s most requested feature so it might be implemented somewhere in the future. It’s achievable in Kotlin to some degree (clever use of delegated properties and extension functions) but the overhead is probably not worth it.