Fundamentals 18 min read

MoonBit Language: Ten Key Features

MoonBit is an AI‑native, general‑purpose programming language that blends Rust and Scala concepts, offering garbage collection, WebAssembly compilation, rich type system, pattern matching, traits, operator overloading, testing support, and functional programming features, illustrated through a chess‑board modeling example.

IT Services Circle
IT Services Circle
IT Services Circle
MoonBit Language: Ten Key Features

MoonBit is a new AI‑native general‑purpose language developed by the Guangdong‑Hong Kong‑Macao Greater Bay Area Digital Economy Institute. It combines the strengths of Rust and Scala while avoiding Rust's borrow‑checker, instead using garbage collection for memory management.

The language can compile to WebAssembly, JavaScript, and other targets, making it suitable for both web and backend development.

Ten Key Features

Fusion of Rust and Scala advantages

No borrow concept from Rust

Garbage‑collected memory model

High performance

WebAssembly compilation

1. Enum Types

MoonBit defines enums for chess pieces and colors, with documentation comments using triple slashes (///) and single‑line comments using double slashes (//). The pubenum keyword makes the definitions public.

/// This application is about a chess board,
/// and how to represent it in the MoonBit language.
pubenum Color {
   White
   Black
}
pubenum Piece {
   Pawn
   Rook
   Knight
   Bishop
   Queen
   King
}

2. Automatic Trait Derivation

Enums can automatically derive Show and Eq traits, enabling direct printing and equality comparison.

pub enum Color {
   ..
} derive(Show, Eq)

pub enum Piece {
   ..
} derive(Show, Eq)

3. Type Aliases

A type alias simplifies complex types. For the chess board, BoardPlace is defined as Option[(Piece, Color)] , representing either an empty square or a piece with a color.

/// This is the representation of a place on a chess board.
/// It can be empty (None) or contain a piece with a color: Some((piece, color)).
pub typealias BoardPlace = Option[(Piece, Color)]

4. Pattern Matching

Pattern matching works like in Scala or Rust. The draw function matches on BoardPlace to return a string representation.

fn draw(self: BoardPlace) -> String {
   match self {
      None => "." // empty place
      Some((piece, Color::White)) => pieceToString.get_or_default(piece, ".")
      Some((piece, Color::Black)) => pieceToString.get_or_default(piece, ".").to_lower()
   }
}

5. Struct Types

Structs model rows, the board grid, and board state, with private fields for encapsulation.

/// This is a struct that represents a row in the board
pub struct Row {
   priv cols: Array[BoardPlace]
} derive(Show, Eq)

pub struct Board {
   priv grid: Array[Row]
}

pub struct BoardState {
   priv board: Board
   priv turn: Turn
}

6. Operator Overloading

The op_get and op_set methods overload the [] operator for indexing rows.

// Overload [] for reading
pub fn op_get(self: Row, index: Int) -> BoardPlace {
   self.cols[index]
}

// Overload [] for assignment
pub fn op_set(self: Row, index: Int, value: BoardPlace) -> Unit {
   self.cols[index] = value;
}

7. Newtype Definitions

Newtypes create distinct types from existing ones. Turn is a newtype based on Color , similar to Scala’s opaque types.

pub type Turn Color

8. Traits (Interfaces)

Traits define abstract behavior. MoonBit provides open traits like Drawable and Paintable , which can be combined using the + operator.

pub (open) trait Drawable {
   draw(Self) -> String
}

pub (open) trait Paintable {
   paint(Self) -> Unit
}

pub trait DrawableAndPaintable : Drawable + Paintable {}

9. Built‑in Testing

Tests are written directly in the source using the test keyword, allowing verification without external frameworks.

test "create a white row from string" {
   let my_row: Row = Row::new_row_from_string!("RNBQKBNR")
   assert_eq!(my_row[0], Some((Piece::Rook, Color::White)))
   // ...additional assertions for each column
}

10. Functional Programming Support

Higher‑order functions, map, and immutable lists are supported. The count function demonstrates recursive pattern matching on a list.

fn count[A](list : @immut/list.T[A]) -> UInt {
   match list {
      Nil => 0
      Cons(*, rest) => count(rest) + 1
   }
}

Beyond the ten features, the article discusses MoonBit’s advantages: garbage collection for easier development, a stable toolchain (the moon CLI and VS Code extension), fast compilation to small WebAssembly binaries, and performance that can rival Rust and Go. It compares MoonBit to Scala, noting similar functional concepts (e.g., last‑expression return) but a smaller, more approachable feature set. The language’s ecosystem is still growing, with around 250 libraries, and includes built‑in JSON handling.

Overall, MoonBit positions itself as a modern, AI‑native language suitable for cloud‑native deployment, offering a blend of functional and systems programming features while remaining accessible to developers familiar with Scala or Rust.

WebAssemblyFunctional ProgrammingMoonBitprogramming languagetype systemCode Example
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.