A Tour of moon

Contents

90 short lessons cover the whole language. Read in order or link directly to any idea.

Progress is stored only in this browser.

Start here

First steps

  1. Hello, moonRun a complete moon program and recognize its entry function.
  2. Read a type errorUse a type annotation and repair a checker diagnostic.
  3. Use another moduleImport a sibling `.mn` module and call one of its public functions.

Values and expressions

Values

  1. Source text and commentsRecognize moon's UTF-8 source, identifiers, separators, and three comment forms.
  2. Numbers and booleansWrite integer bases, separators, floats, and boolean literals.
  3. Strings and interpolationBuild strings with escapes and interpolation.
  4. Bindings and inferenceBind immutable values with inferred or written types.
  5. Mutation and assignmentOpt a binding into mutation and use compound assignment.
  6. Blocks are expressionsUse a block's final expression as a value.
  7. Numeric types and castsChoose a numeric width and make an explicit scalar cast.
  8. Operators and precedenceCombine arithmetic, comparison, logical, and bitwise operators predictably.

Functions

Functions and calls

  1. Declare a functionDeclare typed parameters and return a value from a function.
  2. Return earlyUse `return` to leave a function before its tail expression.
  3. Default argumentsOmit trailing parameters that declare default expressions.
  4. Name call argumentsBind direct-call arguments by parameter name and skip defaults.
  5. Collect variadic argumentsCollect surplus direct-call arguments into a typed array.
  6. Pass function valuesStore and pass a fixed-signature function as a value.
  7. Capture with closuresCreate a closure and observe its by-reference capture.
  8. Write a generic functionInfer a generic type or provide an explicit call type argument.
  9. Evaluate a function at compile timeUse a non-generic function in a compile-time constant expression.

Collections and iteration

Collections

  1. ArraysCreate, index, transform, and mutate a typed dynamic array.
  2. DictionariesStore typed key-value pairs and iterate entries in insertion order.
  3. TuplesGroup positional values and destructure them with a tuple pattern.
  4. Integer rangesUse half-open and inclusive ranges in iteration and patterns.
  5. Eager comprehensionsBuild array and dictionary values from ordered clauses.
  6. Lazy generator expressionsCreate a lazy, single-pass iterator with comprehension syntax.
  7. Iterator cursorsDistinguish aliased and independent single-pass iterators.
  8. N-dimensional arraysConstruct a compact typed ndarray and account for its fallible shape checks.
  9. Build with BytesUse the growable byte buffer for incremental text construction.

Control flow and patterns

Control flow

  1. If expressionsUse `if` for an effect or as a value with matching branches.
  2. Test one pattern with if letOpen one successful optional case without nesting a full match.
  3. While and while letRepeat a boolean condition or drain a fallible iterator pattern.
  4. For loopsConsume an iterable with a fresh, irrefutable pattern per item.
  5. Name a loopTarget an outer loop with labeled break or continue.
  6. Match exhaustivelySelect the first matching arm and close every possible case.
  7. Literal and range patternsRefine numbers and strings with exact, range, and substring patterns.
  8. Structural patternsDestructure tuples and arrays, including a captured remainder.
  9. Guards and or-patternsCombine equivalent patterns and refine a successful binding with a guard.
  10. Publish a refutable bindingUse `let ... else` when successful pattern names must survive the statement.
  11. Optional valuesRepresent presence with `some` and absence with contextual `none`.
  12. Results and propagationReturn typed success or error values and propagate failures with postfix `?`.
  13. See a missing match caseRecognize the checker diagnostic for a non-exhaustive finite match.
  14. Defer block cleanupSchedule LIFO cleanup at the exit of the enclosing block.

User-defined types

Structs, enums, and interfaces

  1. StructsDeclare a named product type and construct or update its fields.
  2. Value and reference semanticsPredict when a binding copies a value or aliases a collection.
  3. Enums with payloadsModel alternatives with unit and payload enum variants.
  4. Contextual enum variantsOmit an enum name when the surrounding type chooses one unambiguously.
  5. Generic structs and enumsParameterize a user-defined product or sum type.
  6. Type aliasesGive a transparent name to an existing type expression.
  7. Inherent methodsAttach behavior to a type and call it through a receiver.
  8. Interfaces and implsSatisfy a method contract and dispatch through an interface value.
  9. Default methods and boundsReuse an interface default and constrain a generic function to its methods.
  10. Associated interface typesBind an interface-owned type member in an implementation.
  11. Overload struct operatorsImplement a reserved inherent method to define a struct operator.
  12. Call a function fieldCall a stored callback through its struct field and understand method precedence.

Modules and projects

Modules, packages, and binaries

  1. Module pathsMap nested module names to directories below the entry file.
  2. Import modules and itemsUse module, single-item, grouped, aliased, and wildcard imports.
  3. Re-export a public surfaceExpose imported public items through a facade module.
  4. Keep module details privateRecognize the diagnostic for importing a private declaration.
  5. Module-owned type identityKeep same-named declarations from different modules as distinct types.
  6. Constants and module stateDistinguish top-level constants from a private mutable module cell.
  7. Package manifestsDeclare a dependency source and import through its package namespace.
  8. Multiple project binariesDeclare explicit and folder-discovered executable entry points.

Memory

Arenas, owners, and resources

  1. What happens by defaultRecognize the allocator and the releases that ordinary code never writes.
  2. Give a block its own memoryReclaim a loop iteration's working values by opening an arena in the body.
  3. Values that leave the blockReturn a value built inside an arena and keep using it afterwards.
  4. Owners free what they holdBuild a Buffer and release it once with defer.
  5. A container owns its elementsMove owned elements into an Array and guard the step that can fail.
  6. Using a value after it is freedRead the check error that reports a use after the value was released.
  7. Storing an arena value somewhere olderRead the check error raised when an owner built in an arena is stored outside it.
  8. Files and processes are owners tooRelease an operating-system resource on every exit from the block that opened it.

Advanced concurrency

Async work, channels, and isolates

  1. Async functions and awaitCreate a lazy future and await its result inside an async function.
  2. Chain a futureTransform a successful future without adding a nested future layer.
  3. Spawn and join tasksStart structured child tasks together and preserve result order.
  4. Select readiness and cancelObserve the first completed future and request cooperative cancellation.
  5. Bounded task channelsSend typed values between cooperative tasks with bounded backpressure.
  6. Use cores with isolatesRun a named top-level function in parallel with isolated state.
  7. Parallel collection workChoose isolate-backed parallelism for CPU-bound collection work.
  8. Share immutable dataPublish immutable strings for shared access across isolates.

Advanced native interop

Checked views and native boundaries

  1. Checked viewsRead and update a Moon value through a checked view.
  2. Mutable receiver methodsUpdate a mutable value through an ordinary receiver method.
  3. External declarationsDistinguish a checked declaration from an executable native binding.
  4. Headers and librariesKeep native build inputs separate from Moon source declarations.
  5. Moon values and C layoutsDistinguish an ordinary Moon value from an imported C layout.
  6. C variadic declarationsDistinguish bare C varargs from a Moon variadic array parameter.
  7. Callbacks and retentionRecognize the ownership obligations of a retained native callback.

Put it together

A small program and local workflow

  1. A small multi-file programCombine modules, user types, collections, results, patterns, and async work.
  2. Write project testsName `test_*` functions and run them with the built-in test command.
  3. Continue locallyMove a tour example into the normal create, check, run, test, format, and lint loop.
  4. Editor support and referencesChoose a shipped editor integration and know when to leave the tour for reference material.