GALA transpiles to Go, so a GALA package is a Go package once it is built. GALA code calls any Go package directly, and Go code calls GALA packages the way it calls other Go packages. The two languages can even share one package. This guide covers both directions with worked examples, how to lay out and build a project that uses both, and the gotchas to know before you start.
For a shorter overview of calling Go from GALA, see Go Interop. The full rules are in the language reference (Go functions that return several results, Go built-in functions, where Go slice and map types may be written).
Every program and Go snippet in this guide is taken from a file in the repository, every one of those files is a test, and a doc test (//internal/doccheck) fails when a listing here stops matching its file. The Bazel examples run in bazel test //examples/go_interop/.... The gala build project runs in the CLI-path CI job, which builds the real CLI with an empty GALA_HOME.
| Section | Files | Test |
|---|---|---|
| Calling Go | examples/go_interop/gala_calls_go/main.gala, Go library warehouse/warehouse.go |
//examples/go_interop:gala_calls_go |
| Implementing Go interfaces | examples/go_interop/go_interfaces/main.gala |
//examples/go_interop:go_interfaces |
| Calling GALA from Go | GALA library pricing/pricing.gala, Go code checkout/checkout.go with Go Example tests |
//examples/go_interop:checkout_test |
| One package, two languages | mixed/textstats/textstats.gala + writer.go |
//examples/go_interop:mixed |
A gala build project |
tools/ci/cli_path/testdata/go_interop/ |
go_interop fixture of tools/ci/cli_path/run_fixtures.sh |
A Go import looks exactly like a Go import. Single, grouped, aliased and dot imports all work, for the standard library, for Go packages in your own module, and for third-party modules. gala_calls_go/main.gala imports the standard library, a GALA package, a hand-written Go package of the same module, and GALA’s Go helpers:
import (
"errors"
"strconv"
"strings"
"time"
. "martianoff/gala/collection_immutable"
"martianoff/gala/examples/go_interop/warehouse"
"martianoff/gala/go_interop"
)
The transpiler decides per import whether the package is GALA or Go. A package is GALA if it is in the current module and contains .gala files, or if it comes from a gala.mod requirement that is not marked // go. Everything else is Go, and its types are read from the Go source by the Go SDK. Nothing has to be declared or generated for a Go package.
A third-party Go module is added with gala mod add github.com/google/uuid@v1.6.0 --go, which writes github.com/google/uuid v1.6.0 // go to gala.mod. Under Bazel it comes from Gazelle’s go_deps like any Go dependency. See Go Dependencies.
When a Go package and a GALA package have the same name (strings, io, json, fs, regex, …), the GALA one keeps the name and you alias the Go one: gostrings "strings".
Go calls look like Go calls. A Go struct is built with named arguments, a Go constructor that returns a pointer works as is, and methods are called through the pointer:
// Go standard library calls look like Go calls.
Println(strings.ToUpper("gala"), strings.Repeat("-", 3), time.Duration(90) * time.Second)
// A Go constructor returning a pointer; methods work through it.
val inv = warehouse.New()
inv.Add(warehouse.Item(SKU = "A-1", Name = "Anvil", Qty = 3, Price = 99.5))
Go field reads (item.Qty), Go constants (time.Second, http.StatusNoContent), variadic calls with spread (ArrayOf(strings.Split(line, ",")...)) and nil arguments all work as in Go.
GALA turns a Go call that returns several results into one value:
| Go returns | A GALA value of type | Read it with |
|---|---|---|
(T, error) |
Try[T] |
match, GetOrElse, Map, FlatMap, bind |
(A, B), including (T, bool) |
Tuple[A, B] |
val (a, b) = … |
(A, B, C) … up to 10 values |
Tuple3 … Tuple10 |
val (a, b, c) = … |
(A, B, error) |
Try[Tuple[A, B]] |
case Success((a, b)) => |
error only |
error |
FromError(call) or Try(call) gives Try[Void] |
This holds for functions and methods alike, from any Go package:
// (T, bool) is a Tuple; destructure it.
func describe(inv *warehouse.Inventory, sku string) string {
val (item, found) = inv.Find(sku)
if (found) s"${item.Name} x${item.Qty}" else s"$sku: no such item"
}
// (T, error) is a Try; match on it. A guard can test the Go error.
func reserve(inv *warehouse.Inventory, sku string, qty int) string = inv.Reserve(sku, qty) match {
case Success(left) => s"reserved $qty of $sku, $left left"
case Failure(err) if errors.Is(err, warehouse.ErrOutOfStock) => s"$sku: not enough stock for $qty"
case Failure(err) => s"failed: ${err.Error()}"
}
// Several fallible Go calls, sequenced with bind.
func parseItem(line string) Try[warehouse.Item] = ArrayOf(strings.Split(line, ",")...) match {
case Array(sku, name, qty, price) => {
bind q = strconv.Atoi(qty)
bind p = strconv.ParseFloat(price, 64)
Success(warehouse.Item(SKU = sku, Name = name, Qty = q, Price = p))
}
case _ => Failure(errors.New(s"want 4 fields: $line"))
}
An error-only call becomes a Try[Void] with FromError:
// An error-only Go call becomes a Try[Void] with FromError.
Println(FromError(inv.Remove("Z-9")).IsFailure())
To hand raw results straight back to Go, bind several names: val n, err = strconv.Atoi(s) gives Go’s two values, with no Try. Prefer the Try in GALA code. Using a Try or Tuple where the plain T is expected is GALA-E0049.
A lambda passed where Go expects a function takes its parameter types from the Go signature, including Go named function types such as warehouse.Predicate (func(Item) bool), http.HandlerFunc or fs.WalkDirFunc:
// A lambda fills a Go named function type (warehouse.Predicate).
val cheap = ArrayFromSlice(inv.Select((i) => i.Price < 5.0))
A Go function type with several results, such as func() (int, error), takes a lambda too. The lambda gives their one GALA value, a Try for (T, error) or a Tuple for (A, B), and Go receives the results. A body that is a Go call with those results returns them as they are, and a generic Go function takes its type arguments from the lambda’s results (Returning several results to Go):
import (
"strconv"
"sync"
)
val port = sync.OnceValues(() => strconv.Atoi("8080")) // a func() (int, error)
val p, err = port()
A GALA type satisfies a Go interface the way a Go type does: by having the methods. No declaration is needed. From go_interfaces/main.gala:
// error: an Error() string method.
struct NotFound(Path string)
func (e NotFound) Error() string = s"not found: ${e.Path}"
// fmt.Stringer: a String() string method; fmt and string interpolation use
// it. Money is an opaque type: a distinct int64 with methods of its own.
opaque type Money int64
func (m Money) String() string = f"$$${float64(m) / 100.0}%.2f"
// sort.Interface over a Go slice held in a field.
struct ByLength(Words []string)
func (b ByLength) Len() int = b.Words.Size()
func (b ByLength) Less(i int, j int) bool = b.Words[i].Size() < b.Words[j].Size()
func (b ByLength) Swap(i int, j int) {
val w = b.Words[i]
b.Words[i] = b.Words[j]
b.Words[j] = w
}
// http.Handler: ServeHTTP(http.ResponseWriter, *http.Request).
struct Greeter(Greeting string)
func (g Greeter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
val name = r.URL.Query().Get("name")
if (name == "") {
http.Error(w, "missing name", http.StatusBadRequest)
} else {
fmt.Fprintf(w, "%s, %s!", g.Greeting, name)
}
}
These values then go straight into Go APIs. A GALA error goes through errors.As, sort.Sort sorts a ByLength, and a Greeter (or a lambda converted to http.HandlerFunc) is served through httptest:
var target NotFound
Println(errors.As(err, &target), target.Path)
// sort.Sort drives a GALA sort.Interface.
val words = ByLength(ArrayOf("banana", "fig", "apple", "kiwi").ToGoSlice())
sort.Sort(words)
val health = http.HandlerFunc((w, r) => w.WriteHeader(http.StatusNoContent))
Pointer receivers. When the methods mutate, declare them on *T and pass the address of a var. A val has no address: &x of one is GALA-E0076. Here a GALA collector receives the Go library’s warehouse.Notifier calls:
struct Collector(Prefix string, var Messages Array[string])
func (c *Collector) Notify(message string) {
c.Messages = c.Messages.Append(s"${c.Prefix}$message")
}
// A pointer to a GALA struct is passed where Go expects an interface.
var collector = Collector("ALERT ", EmptyArray[string]())
val reported = inv.CheckLowStock(10, &collector)
Methods with several results (io.Writer’s Write([]byte) (int, error), io.Reader, json.Marshaler, driver.Valuer) declare Go’s result list. The body gives the results’ one GALA value, a Try for (T, error) or a Tuple for (A, B) (Returning several results to Go):
struct LineCounter(var Lines int)
// io.Writer
func (c *LineCounter) Write(p []byte) (int, error) {
c.Lines = c.Lines + 1
Success(p.Size())
}
A failed Try gives Go the zero value; for an API whose value matters with its error (an io.Reader, a short write), give ResultsOf(goCall(...)) from go_interop instead, in any Go-results body, a lambda passed to a generic Go function such as sync.OnceValues included (Keeping a value returned with an error).
Prefer GALA’s collections in GALA code, and convert at the boundary:
| From | To | Use |
|---|---|---|
Go []T |
Array[T] / List[T] / HashSet[T] |
ArrayFromSlice(s), ListFromSlice(s), HashSetFromSlice(s) (copies), or ArrayOf(s...) |
Array / List / HashSet / TreeSet |
Go []T |
.ToGoSlice() |
Go map[K]V |
HashMap[K, V] / TreeMap[K, V] |
HashMapFromGoMap(m), TreeMapFromGoMap(m) |
HashMap / TreeMap |
Go map[K]V |
.ToGoMap() |
// A Go slice result converts to an immutable Array.
val items = ArrayFromSlice(inv.Items())
Println(items.Map(_.SKU).MkString(", "))
// Back to Go: an Array becomes a Go slice for Go functions that take one.
val names = items.Map(_.Name).ToGoSlice()
Println(strings.Join(names, " | "))
Println(go_interop.SliceAppend(names, "Extra").Size())
Go slice and map types may be written wherever a type is expected (parameters, results, fields, annotations, aliases), but GALA has no slice or map literals (GALA-E0007, GALA-E0008) and no slice expressions. To build or reshape a Go value, use the martianoff/gala/go_interop package. The common cases (the full list is in Go built-in functions):
| Go | GALA |
|---|---|
[]int{1, 2} |
go_interop.SliceOf(1, 2) |
make([]T, n) / make([]T, 0, n) |
SliceWithSize[T](n) / SliceWithCapacity[T](n) |
append(s, x) / append(s, t...) |
SliceAppend(s, x) / SliceAppendAll(s, t) |
s[a:b], s[:n], s[n:] |
Slice(s, a, b), SliceTake(s, n), SliceDrop(s, n) |
map[K]V{} / make(map[K]V) |
MapEmpty[K, V]() |
m[k] = v / delete(m, k) |
MapPut(m, k, v) / MapDelete(m, k) |
v, ok := m[k] |
OptionFromMap(m, k) gives Option[V] |
len(x) |
x.Size(), or .ByteSize() for a string’s bytes |
[]byte(s) / string(b) / []rune(s) |
ToBytes(s) / ToString(b) (or string(b)) / ToRunes(s) |
new(T) |
New[T]() |
| Go | GALA |
|---|---|
go f() |
go_interop.Spawn(() => f()), or a Future from concurrent |
defer x.Close() |
use x = open(...), or Using(res, (r) => ...) from resource |
chan T, select, close(ch) |
Future/Promise/Stream; go_interop.Signal and its helpers (signal channels), CloseChan for Go APIs that hand you one |
panic / recover |
go_builtins.Panic / Try(...) |
if v, err := f(); err != nil |
f() match { ... } or f().GetOrElse(...) (GALA-E0047) |
Struct tags, Name string `json:"name"` |
Codec[T] with .Rename(field, key), .Omit, .OmitEmpty; a type a Go library reads through its tags goes in a .go file of the package (GALA-E0085) |
The bare builtins and statement keywords are compile errors (GALA-E0035, GALA-E0036) whose messages name the replacement.
A Go struct type with no name, such as the struct{} of a signal channel (chan struct{}, or the <-chan struct{} that ctx.Done() returns), has no GALA spelling. GALA still types such a value: it can be bound with val, passed to another Go call and received from (<-done), and a returned struct’s fields can be read. A use that would make the generated Go write the type is GALA-E0090: Some(ctx.Done()), a collection of such values, a lambda that takes or returns one. The go_interop helpers cover signal channels without writing their type:
| Go | GALA (go_interop) |
|---|---|
make(chan struct{}), close(s) |
NewSignal(), CloseSignal(s); a Signal is a named type, so it fits in an Option or a collection |
<-ch; a select with a default; a select with time.After(d) |
WaitClosed(ch), IsClosed(ch), WaitClosedTimeout(ch, d), for any <-chan struct{}, a Signal included |
<-ctx.Done() and the same checks |
WaitDone(ctx), IsDone(ctx), WaitDoneTimeout(ctx, d) |
A Signal passes as it is to a Go API that takes a chan struct{} or a <-chan struct{}, as Go allows. A struct with fields that your own Go code returns can be given a name on the Go side.
A GALA package is a Go package after transpilation. Go code imports it by its import path, and nothing is generated for the Go side. What Go sees is the generated code, so it helps to know its shape.
| GALA | Go sees |
|---|---|
func Subtotal(items Array[LineItem]) int64 |
the same function. Default parameter values exist only for GALA callers, so Go passes every argument |
struct LineItem(SKU string, ...) (fields not var) |
type LineItem struct { SKU std.Immutable[string]; ... } and a generated constructor NewLineItem(...). Read a field with item.SKU.Get() |
var field, e.g. type Receipt struct { var TotalCents int64 } |
a plain Go field TotalCents int64 |
sealed type Discount { case Percent(Pct int64) ... } |
one struct Discount (unexported tag), an empty struct per case (Percent{}.Unapply(d) returns std.Option[int64]), generated constructors (NewDiscountPercent(...) builds a case) and case predicates (d.IsPercent()) |
Option[T], Try[T], Either[L, R] |
std.Option[T] etc.: IsDefined(), IsSuccess(), Get(), GetError(), GetOrElse(x) |
a generic method, e.g. Option.Map[U] |
a free function std.Option_Map(o, f) (Go methods cannot have type parameters) |
a method of a generic type whose signature names another generic type, e.g. Array.ToList(), HashMap.Keys() |
a free function collection_immutable.Array_ToList(arr), unless an interface the declaring package sees has a method of that name (Iterable, Seq, …). Go compiles every method of a generic type for each type argument, so a method that brings in another generic type is a function, compiled only where it is called |
Array[T], List[T], HashMap[K, V] |
collection_immutable.Array[T] etc.: ArrayOf, ArrayFromSlice, .Size(), .ToGoSlice() |
package-level var X / val X |
a Go variable / a std.Immutable variable (read with X.Get()) |
func Step(inout p Parser), func (inout p Parser) Advance() |
the same function and pointer method, which lend the GALA body a copy; GALA code calls the body, GALA_Step or GALA_Parser_Advance |
| PascalCase / camelCase names | exported / unexported, exactly as in Go. GALA never renames an identifier |
Every type also gets Copy(), Equal(other) and, for sealed types, String().
inout functions and methodsAn inout parameter promises the callee an
exclusive place for the call. Go makes no such promise: it may pass a
pointer it keeps, shares with another goroutine, or passes twice. So an
exported function or method with an inout parameter or receiver keeps its
Go signature, but Go calls a wrapper that lends the GALA body a copy:
// func Transfer(inout from Account, inout to Account, amount int) in GALA
func Transfer(from *Account, to *Account, amount int) {
_gala_in_from := *from // copy in
_gala_in_to := *to
GALA_Transfer(&_gala_in_from, &_gala_in_to, amount)
*from = _gala_in_from // copy out, on a normal return only
*to = _gala_in_to
}
// GALA_Transfer is generated: it is the GALA body of Transfer, ...
func GALA_Transfer(from *Account, to *Account, amount int) { ... }
Transfer. An inout method stays a Go method with a
pointer receiver, func (a *Account) Deposit(amount int) int, so method
sets and interfaces work as for any pointer method.GALA_Transfer, or GALA_Account_Deposit(&a, amount) for an
inout method, and pays no copies. The GALA_ prefix is reserved
(GALA-E0097), so these names cannot clash with a
declaration of yours; two generated names that would clash are GALA-E0111.
Some calls keep calling the wrapper, which is just as correct and costs the
two copies: a function value (val f = Transfer), a call through an
interface, a method with a Ptr receiver, a generic method, and a method
that declares a Go result list.Transfer(a, a, 5) from Go copies *a twice and
copies both back, left to right: the last write wins.*a through its own pointer while
the body runs sees the value from before the call.Ptr[T] instead.A non-exported inout function gets a wrapper too, since Go files of its
own package can call it. One that lends a place of a type that must not be
copied (a strings.Builder) has none, and only GALA can call it; an exported
one is GALA-E0111.
The other direction is narrower. GALA lends an inout place to Go only where
Go provably keeps no reference to it: a Go pointer method on the compiler’s
no-retain allow-list (bytes.Buffer.WriteString, strings.Builder.Grow,
…). Each entry is checked in CI against the pinned Go compiler’s escape
analysis, and programs cannot add entries. Any other Go call that would get
the place’s address is GALA-E0113; copy the place
first (var tmp = b, call Go on tmp, then b = tmp). strings.Builder’s
write methods are not on the list: they store the builder’s own address.
The Ownership guide walks through both directions with a tested example, and lists the whole allow-list.
Go compiles every method of a generic type once for each type argument, whether or not anything calls it. A method whose signature names another generic type would make every Array[T] compile a List[T], an Option[Array[T]] and their methods too. GALA therefore generates such a method as a free function, which Go compiles only where it is called. GALA code calls it as a method, arr.ToList(). Go code calls the function:
list := collection_immutable.Array_ToList(arr) // arr.ToList() in GALA
keys := collection_immutable.HashMap_Keys(m) // m.Keys()
tail := collection_immutable.Array_TailOption(arr) // arr.TailOption()
A method stays a Go method when any of these holds:
Size(), Filter(p), Append(x) on Array[T]);Iterable, Seq, Traversable, Hashable and Ordered: HeadOption(), Partition(p) and SplitAt(n) stay methods;String, GoString, Format, Error, Unwrap, Is, As, Equal, Copy, Hash, Compare, Get, Apply, Unapply, MatchView, IsZero and the Marshal/Unmarshal JSON, text, YAML and binary methods;Load() (List[T], error).Because a function is not in a type’s method set, the type does not implement an interface, declared somewhere its package cannot see, that needs the method. GALA reports both uses of such an interface: a value used as one is GALA-E0100, and a type pattern testing for one is GALA-E0109.
== in Go is Go’s. In GALA, a == b on a struct, sealed type, tuple or collection calls a.Equal(b) (Equality). Go code that compares GALA values with == gets Go’s operator: two Lists built separately with the same elements are not == in Go, and a GALA struct holding a collection or a val field compares the internal fields. Call a.Equal(b) from Go for GALA’s meaning.
Go can make a value without running any GALA code: Discount{} is a composite literal and var d Discount a zero value. Neither applies the defaults GALA declares. So an exported sealed type comes with constructors for Go callers, and its Godoc says to use them:
| Generated | When | What it does |
|---|---|---|
NewT() |
T has a default case |
returns T’s default value: the default case, with every field default applied |
NewT<Case>(...) |
for each exported case | builds that case. Each field without a default is a parameter, in order. The fields with a default are options |
With<T><Case><Field>(v) |
for each field with a default | an option for NewT<Case> that sets that field; the other fields keep their defaults |
Discount in the example below declares default case NoDiscount() and case Percent(Pct int64 = 10), so Go sees:
// Discount is a sealed type: one Go struct, a type per case, and generated
// Go constructors. NoDiscount is its default; Percent's Pct defaults to 10.
// Use NewDiscount for the default value (NoDiscount), or a case constructor: NewDiscountNoDiscount, NewDiscountPercent, NewDiscountAmountOff.
type Discount struct { /* unexported fields */ }
// NewDiscount returns Discount's default value: NoDiscount, what GALA uses where none is given.
func NewDiscount() Discount
// NewDiscountNoDiscount returns the NoDiscount case of Discount.
func NewDiscountNoDiscount() Discount
// NewDiscountPercent returns the Percent case of Discount, each option applied over its field defaults (Pct 10).
func NewDiscountPercent(_opts ...DiscountPercentOption) Discount
// WithDiscountPercentPct sets Percent's Pct (default 10).
func WithDiscountPercentPct(v int64) DiscountPercentOption
// NewDiscountAmountOff returns the AmountOff case of Discount.
func NewDiscountAmountOff(cents int64) Discount
Calling them from Go:
pricing.NewDiscount() // NoDiscount()
pricing.NewDiscountPercent() // Percent(10)
pricing.NewDiscountPercent(pricing.WithDiscountPercentPct(50)) // Percent(50)
pricing.NewDiscountAmountOff(100) // AmountOff(100)
NewT. The Godoc then says the type has no default value and that its zero value is none of its cases. A GALA match on such a zero value panics.T{} holds Go’s zero values instead. Use NewT().sealed type Box[T any] { case Full(Value T) ... } gives func NewBoxFull[T any](value T) Box[T]. An option carries all of the type’s parameters, and Go cannot infer them from an option’s argument, so write them out: NewBoxFull("a", WithBoxFullCount[string](2)).SKU → sku, URLPath → urlPath). A name that is a Go keyword or an imported package gets a trailing underscore (type_).NewDiscount itself, in a .gala file or a hand-written .go file, or two of its types would generate the same name, that constructor is left out. Test files are not consulted, so a test that declares one of these names fails with “redeclared”. Every name a case constructor needs (its options included) must be free, or the whole case constructor is skipped. Go code then uses Percent{}.Apply(...), which takes every field.For the same reason, an exported shorthand struct gets New<T>(...): each field without a default is a parameter, in order, and each field with one is an option, With<T><Field>(v), applied over its default. The constructor wraps each immutable field in std.Immutable, so Go passes plain values. LineItem in the example below declares struct LineItem(SKU string, UnitCents int64, Qty int = 1), so Go sees:
// LineItem is GALA-native: its fields are immutable, so Go sees each one as
// a std.Immutable[T] and builds a LineItem through the generated NewLineItem.
// Qty defaults to 1.
// From Go, create it with NewLineItem. A composite literal LineItem{} does not apply GALA's field defaults: its fields hold Go's zero values.
type LineItem struct {
SKU std.Immutable[string]
UnitCents std.Immutable[int64]
Qty std.Immutable[int]
}
// NewLineItem returns a new LineItem, each option applied over its field defaults (Qty 1).
func NewLineItem(sku string, unitCents int64, _opts ...LineItemOption) LineItem
// WithLineItemQty sets LineItem's Qty (default 1).
func WithLineItemQty(v int) LineItemOption
pricing.NewLineItem("A-1", 1000) // Qty 1
pricing.NewLineItem("A-1", 1000, pricing.WithLineItemQty(3)) // Qty 3
The naming rules above apply. A struct with an unexported field gets no constructor, since GALA lets only its own package set that field; export one by hand when Go needs it. A struct without fields, or a block-form struct (type Cfg struct { ... }), which has no field defaults, gets none either: Go builds it with a composite literal.
Each exported case of an exported sealed type has a predicate Is<Case>(), so Go can test a value’s case in an if or a switch and read its fields with the case’s Unapply:
switch {
case d.IsPercent():
return fmt.Sprintf("%d%% off", pricing.Percent{}.Unapply(d).Get())
case d.IsAmountOff():
return fmt.Sprintf("%d cents off", pricing.AmountOff{}.Unapply(d).Get())
}
A predicate is not generated when the type declares a method of that name or has a field of it; the standard library’s Either.IsLeft() and Try.IsSuccess() are its own methods, and Option gains IsSome() and IsNone() next to IsDefined() and IsEmpty(). Constructors and predicates are for Go callers: GALA code builds values by calling the type and tests a case with match.
The language reference covers the rules for constructors.
pricing/pricing.gala is a GALA library written to be called from Go. It gives its immutable struct and its sealed type field defaults, its sealed type a default case, uses var fields on the struct Go reads most, and returns Option and Try:
package pricing
import (
"errors"
"strconv"
"strings"
. "martianoff/gala/collection_immutable"
)
// LineItem is GALA-native: its fields are immutable, so Go sees each one as
// a std.Immutable[T] and builds a LineItem through the generated NewLineItem.
// Qty defaults to 1.
struct LineItem(SKU string, UnitCents int64, Qty int = 1)
// Receipt is Go-shaped: `var` fields are plain Go fields.
type Receipt struct {
var TotalCents int64
var Lines int
var Note string
}
// Discount is a sealed type: one Go struct, a type per case, and generated
// Go constructors. NoDiscount is its default; Percent's Pct defaults to 10.
sealed type Discount {
default case NoDiscount()
case Percent(Pct int64 = 10)
case AmountOff(Cents int64)
}
// ErrEmptyCart is a plain Go error value that Go can test with errors.Is.
var ErrEmptyCart = errors.New("empty cart")
// Subtotal sums an immutable Array of items.
func Subtotal(items Array[LineItem]) int64 =
items.FoldLeft(int64(0), (acc, i) => acc + i.UnitCents * int64(i.Qty))
// Apply is a method on the sealed type.
func (d Discount) Apply(cents int64) int64 = d match {
case NoDiscount() => cents
case Percent(p) => cents - cents * p / 100
case AmountOff(c) => if (c > cents) int64(0) else cents - c
}
// amount reads the number after a coupon's prefix.
func amount(code string, prefix string) Option[int64] =
strconv.ParseInt(strings.TrimPrefix(code, prefix), 10, 64).ToOption()
// ParseCoupon returns None for a code it does not know.
func ParseCoupon(code string) Option[Discount] = code match {
case "" => Some(NoDiscount())
case c if strings.HasPrefix(c, "PCT") => amount(c, "PCT").Map((n) => Percent(n))
case c if strings.HasPrefix(c, "OFF") => amount(c, "OFF").Map((n) => AmountOff(n))
case _ => None()
}
// Checkout fails with ErrEmptyCart or an unknown-coupon error.
func Checkout(items Array[LineItem], coupon string) Try[Receipt] = ParseCoupon(coupon) match {
case _ if items.IsEmpty() => Failure(ErrEmptyCart)
case Some(d) => Success(Receipt(
TotalCents = d.Apply(Subtotal(items)),
Lines = items.Size(),
Note = d.String(),
))
case None() => Failure(errors.New(s"unknown coupon $coupon"))
}
checkout/checkout.go is ordinary Go that imports pricing. It converts Go input into GALA values, turns a Try into Go’s (value, error), reads a sealed value and maps an Option:
package checkout
import (
"errors"
"fmt"
"martianoff/gala/collection_immutable"
"martianoff/gala/examples/go_interop/pricing"
"martianoff/gala/std"
)
// Line is the Go-side input: a plain Go struct.
type Line struct {
SKU string
UnitCents int64
Qty int
}
// toItems converts Go values into the immutable Array the GALA API takes.
func toItems(lines []Line) collection_immutable.Array[pricing.LineItem] {
items := make([]pricing.LineItem, 0, len(lines))
for _, l := range lines {
items = append(items, pricing.NewLineItem(l.SKU, l.UnitCents, pricing.WithLineItemQty(l.Qty)))
}
return collection_immutable.ArrayFromSlice(items)
}
// Total runs the GALA checkout and turns its Try into Go's (value, error).
func Total(lines []Line, coupon string) (int64, error) {
result := pricing.Checkout(toItems(lines), coupon)
if result.IsFailure() {
return 0, result.GetError()
}
return result.Get().TotalCents, nil
}
// Describe reads a GALA sealed value from Go: IsPercent and IsAmountOff test
// its case, and the case's Unapply returns its fields.
func Describe(d pricing.Discount) string {
switch {
case d.IsPercent():
return fmt.Sprintf("%d%% off", pricing.Percent{}.Unapply(d).Get())
case d.IsAmountOff():
return fmt.Sprintf("%d cents off", pricing.AmountOff{}.Unapply(d).Get())
}
return "no discount"
}
// CouponLabel calls a GALA function that returns an Option and maps it with
// a Go func. Generic methods such as Option.Map are free functions in Go.
func CouponLabel(code string) string {
label := std.Option_Map(pricing.ParseCoupon(code), Describe)
return label.GetOrElse("unknown coupon")
}
// IsEmptyCart tests a GALA-declared Go error value with errors.Is.
func IsEmptyCart(err error) bool {
return errors.Is(err, pricing.ErrEmptyCart)
}
The Go Example tests in checkout_test.go check the output. One of them builds GALA values directly from Go:
func Example_fromGo() {
discount := pricing.NewDiscountPercent(pricing.WithDiscountPercentPct(50))
fmt.Println(discount, discount.Apply(900))
fmt.Println(pricing.NewDiscountPercent(), pricing.NewDiscount())
item := pricing.NewLineItem("C-3", 475, pricing.WithLineItemQty(2))
fmt.Println(item.SKU.Get(), item.Qty.Get())
items := collection_immutable.ArrayOf(item, pricing.NewLineItem("D-4", 50))
fmt.Println(items.Size(), pricing.Subtotal(items))
receipt := pricing.Checkout(items, "OFF100").Get()
fmt.Println(receipt.TotalCents, receipt.Lines, receipt.Note)
// Output:
// Percent(50) 450
// Percent(10) NoDiscount()
// C-3 2
// 2 1000
// 900 2 AmountOff(100)
}
Designing a GALA API for Go callers:
default case when it has a natural default, and declare field defaults. Go then gets NewT() and options on NewT<Case>, and doesn’t need to know the defaults.NewX(...) function for each immutable struct Go must build. The alternative, X{F: std.NewImmutable(v)}, works but is noisy.var fields, or the block form type X struct { var F T }, on result types that Go reads a lot.Describe above) for sealed types instead of making every caller chain Unapply calls.error values (errors.New, a struct with Error()), so errors.Is and errors.As work on both sides.A package can hold both .gala and hand-written .go files. They are one Go package after transpilation, so each side calls the other’s declarations, exported or not, without an import. Reach for this when you need:
Write below works on raw bytes).select, unsafe, cgo, or code generated by another tool.mixed/textstats/textstats.gala:
package textstats
import (
"strings"
. "martianoff/gala/collection_immutable"
)
// Counter is written to by Go's io functions through the Write method in
// writer.go. Its fields are `var`, so Go sees plain fields; inWord carries a
// word that one Write ends and the next continues.
struct Counter(var Lines int, var Words int, var Bytes int, var inWord bool = false)
// Stats is the immutable summary GALA code works with.
struct Stats(Lines int, Words int, Bytes int, Longest string)
// countWords is unexported GALA that writer.go calls.
func countWords(text string) int = strings.Fields(text).Size()
// longestWord is used by Summarize.
func longestWord(text string) string =
ArrayOf(strings.Fields(text)...).FoldLeft("", (best, w) => if (w.Size() > best.Size()) w else best)
// Summarize calls CountReader, a Go function from writer.go. It returns
// (Counter, error), so GALA sees a Try[Counter].
func Summarize(text string) Try[Stats] =
CountReader(strings.NewReader(text)).Map((c) => Stats(c.Lines, c.Words, c.Bytes, longestWord(text)))
mixed/textstats/writer.go, in the same directory and the same package:
package textstats
import (
"encoding/json"
"io"
"strings"
"unicode"
"unicode/utf8"
)
// Write makes *Counter an io.Writer. A Go file in the same package can add
// a method to the GALA struct; this one works on raw bytes, which reads more
// simply in Go. A caller may split its input across several writes (io.Copy
// writes 32 KB at a time), so a word cut in two is counted once.
func (c *Counter) Write(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
text := string(p)
c.Bytes += len(p)
c.Lines += strings.Count(text, "\n")
c.Words += countWords(text) // unexported GALA function, same package
first, _ := utf8.DecodeRune(p)
if c.inWord && !unicode.IsSpace(first) {
c.Words-- // the previous write ended inside this word
}
last, _ := utf8.DecodeLastRune(p)
c.inWord = !unicode.IsSpace(last)
return len(p), nil
}
// CountReader copies r into a Counter with Go's io.Copy.
func CountReader(r io.Reader) (Counter, error) {
var c Counter
_, err := io.Copy(&c, r)
return c, err
}
// MarshalJSON makes Stats a json.Marshaler with lowercase keys. Its fields are
// immutable, which Go sees as std.Immutable[T] values; Get reads them.
func (s Stats) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{
"lines": s.Lines.Get(),
"words": s.Words.Get(),
"bytes": s.Bytes.Get(),
"longest": s.Longest.Get(),
})
}
From the outside the package is a single package. mixed/main.gala uses the Go-declared methods on the GALA types:
package main
import (
"encoding/json"
"fmt"
"martianoff/gala/examples/go_interop/mixed/textstats"
)
func main() {
val text = "GALA transpiles to Go\nand Go calls GALA back\n"
textstats.Summarize(text) match {
case Success(stats) => {
Println(s"lines=${stats.Lines} words=${stats.Words} longest=${stats.Longest}")
// Stats.MarshalJSON is declared in Go, so encoding/json uses it.
Println(json.Marshal(stats).Map((b) => string(b)).GetOrElse("cannot encode"))
}
case Failure(err) => Println(s"failed: ${err.Error()}")
}
// *Counter is an io.Writer, so fmt.Fprintf can write into a GALA struct.
var counter textstats.Counter
fmt.Fprintf(&counter, "%d words\n", 3)
Println(s"lines=${counter.Lines} words=${counter.Words} bytes=${counter.Bytes}")
// A word split across two writes counts once.
fmt.Fprint(&counter, "split wo")
fmt.Fprint(&counter, "rd\n")
Println(s"lines=${counter.Lines} words=${counter.Words} bytes=${counter.Bytes}")
}
lines=2 words=9 longest=transpiles
{"bytes":45,"lines":2,"longest":"transpiles","words":9}
lines=1 words=2 bytes=8
lines=2 words=4 bytes=19
Rules for a mixed package:
package name and one namespace, so a name declared in both a .gala and a .go file is a duplicate.Copy, Equal, Unapply, and for sealed types String. For an opaque type, a hand-written Hash or Compare replaces the generated one.x.gen.go next to an x.gala, or x_test.gen_test.go next to an x_test.gala: gala build writes the .gala file’s output under that name and rejects the clash.A module built with plain go build instead of gala build can commit the transpiled files; see Committing transpiled files to a plain Go module.
gala CLIgala build, gala run and gala test build .gala and .go files together. The project below is the go_interop fixture in tools/ci/cli_path/testdata/go_interop, which CI builds with a CLI built from the same sources:
go_interop/
├── gala.mod module example.com/gointerop
├── go.mod
├── main.gala GALA main: calls Go (helper.go, report) and GALA (textstats)
├── helper.go Go in package main: calls GALA (exclaim) and Go (report)
├── textstats/ one package of GALA plus hand-written Go (Part 3)
│ ├── textstats.gala
│ └── writer.go
├── report/
│ └── report.go plain Go importing the GALA package textstats
└── cmd/gomain/
└── main.go a Go main package calling GALA through report
report/report.go imports example.com/gointerop/textstats, a GALA package, like any other package of the module..go files next to main.gala belong to package main too. helper.go calls exclaim, a function declared in main.gala, and main.gala calls helper.go’s functions.main package works too. gala build -o gomain ./cmd/gomain builds a binary whose main is Go and which reaches GALA through its imports.gala.mod with // go (gala mod add ... --go). Use gala mod tidy, not go mod tidy.Generated Go is written to a build workspace under GALA_HOME, not to your source tree. A plain go build does not understand .gala files, so build with gala (or Bazel). A Go module built with plain go build can use GALA code that gala export wrote as a Go module (Part 5).
A Go library is an ordinary deps entry of a GALA target, and a gala_library is an ordinary dependency of a go_library, go_binary or go_test. The two wirings that need GALA’s rules are a package that mixes both languages, and a GALA dependency whose constructors the code uses. From examples/go_interop/BUILD.bazel:
go_library(
name = "checkout",
srcs = ["checkout/checkout.go"],
importpath = "martianoff/gala/examples/go_interop/checkout",
deps = [
":pricing",
"//collection_immutable",
"//std",
],
)
gala_library(
name = "textstats",
srcs = ["mixed/textstats/textstats.gala"],
go_srcs = ["mixed/textstats/writer.go"],
importpath = "martianoff/gala/examples/go_interop/mixed/textstats",
deps = ["//collection_immutable"],
)
gala_exec_test(
name = "mixed",
src = "mixed/main.gala",
expected = "mixed/main.out",
gala_deps = [":textstats"],
)
checkout is Go depending on the GALA library :pricing. textstats puts the hand-written Go in go_srcs. mixed lists :textstats in gala_deps, the recommended place for a GALA dependency: the transpiler then reads its source, which a call to one of its struct or sealed-case constructors needs (from deps alone the transpiler cannot tell such a call from a Go conversion). Gazelle (bazel run //:gazelle) generates these targets for GALA, Go and mixed packages. See Bazel Integration for MODULE.bazel, third-party Go modules and the deps/gala_deps split.
Parts 2 to 4 build Go and GALA together with gala or Bazel. A Go module built with plain go build cannot do that: the go command does not transpile .gala files, and it cannot download GALA’s standard library, which GALA code imports as martianoff/gala/... (a path whose first element has no dot). Three things close the gap:
go.gala.fyi/stdlib is the standard library as an ordinary Go module. Every GALA release publishes it at the same version (GALA 0.87.0 is v0.87.0), with its imports rewritten to go.gala.fyi/stdlib/... and one go.mod with no replace directives.gala export writes your GALA project as an ordinary Go module: its generated and hand-written Go, with standard library imports rewritten to go.gala.fyi/stdlib, and a go.mod that requires it. Publish that, and Go programs import your library with go get.gala transpile --stdlib-module writes one generated file’s standard library imports as go.gala.fyi/stdlib/..., for a Go module that commits a few transpiled .gala files next to its Go code.GALA source, gala build and Bazel are unchanged: they keep using martianoff/gala/....
Which one fits:
| Situation | Use |
|---|---|
A GALA project built with gala build / gala run |
nothing: its imports already resolve |
| A Bazel build with rules_gala | nothing (and never --stdlib-module) |
Go code that wants GALA’s collections, Option or Try |
require go.gala.fyi/stdlib (The standard library) |
A library written in GALA that Go programs should go get |
gala export (Exporting a GALA library) |
A Go module that commits the output of a few .gala files |
gala transpile --stdlib-module (Committing transpiled files) |
go get go.gala.fyi/stdlib@latest
tools/ci/go_export/consumer/main.go.tmpl uses it. CI exports the standard library from every pull request and builds this program against it with go mod tidy and go run, with no gala on PATH:
package main
import (
"fmt"
"strconv"
ci "go.gala.fyi/stdlib/collection_immutable"
"go.gala.fyi/stdlib/std"
)
func main() {
nums := ci.ArrayOf(1, 2, 3, 4)
sum := ci.Array_FoldLeft(nums, 0, func(acc, n int) int { return acc + n })
fmt.Println(nums.MkString(","), sum) // 1,2,3,4 10
// Generic GALA methods are free functions in Go: Option.Map is Option_Map.
label := std.Option_Map(std.Some[int]{}.Apply(7), strconv.Itoa)
fmt.Println(label.GetOrElse("none")) // 7
}
0.87.0-rc.1 is v0.87.0-rc.1). Publishing started with the first release after 0.86.0. A published version never changes.std.Option_Map), immutable fields are read with .Get(), and sealed cases are told apart with Unapply.martianoff/gala. Go treats go.gala.fyi/stdlib/std and martianoff/gala/std as different packages, so an Option from one is not an Option of the other, and each copy has its own package state, such as concurrent’s global execution context. Use one or the other in a program.tools/ci/go_export/testdata/shapes is a GALA library, module example.com/shapes, with a sealed type Shape, a subpackage units, and a hand-written shapes.go. gala export, run in the project, writes it as a Go module:
gala export --out ../shapes-go
shapes-go/
├── go.mod module example.com/shapes; require go.gala.fyi/stdlib v0.87.0
├── VERSION the gala version and commit that wrote it
├── shapes.gen.go from shapes.gala
├── shapes.go hand-written Go, copied as it is
└── units/units.gen.go from units/units.gala
gala build does it for a library. The export holds every package except tests, with the project’s own imports under its module path and standard library imports rewritten to go.gala.fyi/stdlib. gala.mod and Bazel files are left out.go.mod requires go.gala.fyi/stdlib at the version of the gala that exported it, plus every Go module the code needs, as go mod tidy resolves them for gala build: the // go requirements of gala.mod and the modules they bring in.--go-module sets the path Go programs import the export by. It defaults to the project’s module path, and it must be a path the go command can download: one whose first element is a domain, such as github.com/you/shapes.--out outside the project: the whole project is exported.gala.mod that replaces a Go module, since a published module’s replace directives do not apply to the programs that import it.Publishing. The go command downloads a module from the repository its path names, reading the files committed at a vX.Y.Z tag. So the export must be what is committed at that tag:
gala export --go-module github.com/you/shapes-go --out ../shapes-go, commit the directory’s contents there, and tag the commit.vX.Y.Z. The tag keeps the commit reachable, and the main branch keeps your GALA sources.A Go program then imports the library like any Go module. CI exports example.com/shapes from every pull request and builds this program against it, resolving both modules with go mod tidy through a module proxy:
package main
import (
"fmt"
"example.com/shapes"
ci "go.gala.fyi/stdlib/collection_immutable"
)
func main() {
// Sealed-type cases are built with Apply on the case's Go type.
all := ci.ArrayOf(shapes.Circle{}.Apply(1), shapes.Rect{}.Apply(2, 3))
fmt.Println(shapes.Area(all.Get(0)), shapes.Area(all.Get(1))) // 3.14 6
largest := shapes.Largest(all)
fmt.Println(largest.Get()) // Rect(2, 3)
none := shapes.Largest(ci.EmptyArray[shapes.Shape]())
fmt.Println(none.IsDefined()) // false
}
Versions. Generated code calls the standard library’s own helpers, so export a library with the GALA release you build it with. When a Go program uses several exported libraries, Go picks the highest go.gala.fyi/stdlib version any of them requires, so export the libraries one program combines with the same GALA release.
A GALA library that is not published for Go. Most GALA libraries, gala-tui among them, are released for GALA only. A Go program can still use one: export a checkout of the release it wants, and point the program at the export with a replace:
git clone --branch 0.15.4 https://github.com/martianoff/gala-tui
cd gala-tui && gala export --out ../gala-tui-go
// in the Go program's go.mod
require github.com/martianoff/gala-tui v0.0.0
replace github.com/martianoff/gala-tui => ../gala-tui-go
go mod tidy then fetches go.gala.fyi/stdlib and the library’s Go dependencies as usual; only the library itself comes from the export. Commit the export, or script the two commands, so every build of the program gets the same one.
Some Go modules hold a few .gala files among their Go code and commit the Go that gala transpile writes for them, the layout of Part 3 without gala build. Everyone else builds the module with plain go build and needs no GALA; only whoever edits a .gala file runs gala. By default the generated file imports martianoff/gala/..., which the go command cannot download, so such a file could not use the standard library at all. --stdlib-module writes those imports under the published module instead:
cd p && gala transpile -i p.gala -o p.go --stdlib-module go.gala.fyi/stdlib
Run it in the package directory with relative paths: the generated file’s //line comments name the input as given, and committed files should not depend on where they were generated.
With the module’s go.mod requiring the standard library at the version of that gala (gala version), go build resolves the imports like any other dependency:
module example.com/server
go 1.25
require go.gala.fyi/stdlib v0.87.1
package p
import . "martianoff/gala/collection_immutable"
func Names() string = ArrayOf(1, 2, 3).MkString(",")
The generated p/p.go then imports go.gala.fyi/stdlib/std and go.gala.fyi/stdlib/collection_immutable, and Go code in the module calls p.Names() as usual. A //go:generate line next to the .gala file keeps the command in one place:
//go:generate gala transpile -i p.gala -o p.go --stdlib-module go.gala.fyi/stdlib
require exactly the version of the gala that wrote the files. To upgrade, regenerate every file with the new gala and change the require in the same commit.martianoff/gala/std, a different package from go.gala.fyi/stdlib/std (see The standard library), so its Option is not the other files’ Option.gala build and Bazel resolve martianoff/gala/... themselves, and --stdlib-module cannot be combined with gala transpile --run..gala file that imports another GALA module, such as gala-tui, still needs that module as Go, for example through gala export.gala transpile can leave a .gala/ cache directory in the module; add .gala/ to .gitignore.gala transpile-package takes the same flag for several files of one package.gala stdlib export and gala export work with a gala built from your checkout too (bazel run //cmd/gala -- ..., which resolves relative paths from the directory you run it in). Export the standard library under a version that will never be published, and the library against it:
gala stdlib export --go-module go.gala.fyi/stdlib --out ../stdlib-export \
--proxy ../goproxy --version v0.0.0-local.1
gala export --out ../shapes-go --stdlib-version v0.0.0-local.1 \
--proxy ../goproxy --version v0.1.0
--out must be empty and outside any Bazel workspace. A Go module then uses the exports in one of two ways:
go work init . ../stdlib-export ../shapes-go makes the module’s imports resolve to the exports, with no change to its go.mod.A local module proxy, which goes through go get the way a published version does. --proxy writes each export as module version --version, in the layout GOPROXY=file:// serves:
GOPROXY=file://$PWD/../goproxy,https://proxy.golang.org GONOSUMDB=go.gala.fyi/stdlib,example.com/shapes \
go get example.com/shapes@v0.1.0
GONOSUMDB is needed because the checksum database only knows published versions. Use versions that will never be published, such as v0.0.0-local.N: a local zip under a real version number would clash with the published one in go.sum.
A maintainer can also publish a standard library build from any branch without a release. Running the Publish stdlib for Go consumers workflow with the dev channel pushes it to the dev branch of the module’s repository, and go get go.gala.fyi/stdlib@dev fetches it.
A checklist of what differs from writing Go. The first ones are covered in the parts above and are listed here so nothing is missed.
Calling Go from GALA
(T, error) call is a Try[T], not a T, and (A, B) is a Tuple (table). Using one as the plain value is GALA-E0049. val (data, err) = os.ReadFile(p) is an error too, because a Try is not a Tuple: val data, err = os.ReadFile(p), without parentheses, gives Go’s raw values. Don’t wrap a (T, error) call in Try(...). It is already a Try.if initializer. if n, err := strconv.Atoi(s); err != nil is GALA-E0047. Use match or GetOrElse.&x of a var to Go. A val, a parameter and a receiver have no address: &x of one is GALA-E0076 (pointer receivers).var. With val sb = strings.Builder{}, the call sb.WriteString(...) is GALA-E0053 because the pointer method would run on a copy. Write var sb strings.Builder, and the same for bytes.Buffer, sync.Mutex and the sync/atomic types.val, or an immutable field, that holds a Go slice, map or pointer shares it, so Go code (or an index assignment) can still change what it points to. sort.Sort(words) above sorts the slice inside an immutable field. Convert to Array/HashMap when the contents must not change.chan, select, go or defer. Each has a replacement (slices and maps, Go features without GALA syntax), and the compiler error names it.gostrings "strings". A Go keyword used as a name (type, func, range, …) is GALA-E0055. GALA never renames an identifier, because Go code would see the new name.go on PATH (or GOROOT), transpiling still works, but Go result types are unknown and calls that depend on them fail to infer.Calling GALA from Go
std.Immutable[T]. Go reads them with .Get() and cannot assign them. Go can build a struct with std.NewImmutable(v) per field, but an exported NewX constructor reads better. Generating one is a proposed extension (#688).encoding/json, YAML libraries (gopkg.in/yaml.v2, v3) and fmt encode, decode and print an exported immutable field as the value it holds, keyed by the field’s name. GALA has no struct tags (GALA-E0085); for other keys, use Codec[T] from json or yaml. A json.Decoder’s DisallowUnknownFields and UseNumber do not reach inside the field.NewT(), NewT<Case>(...)), not a composite literal. T{} skips field defaults, and for a type without a default case it is none of its cases.Unapply, because the variant tag is unexported: (pricing.Percent{}).Unapply(d).IsDefined(). A GALA helper such as Describe above is friendlier.opt.Map(f) in GALA is std.Option_Map(opt, f) in Go, and arr.FoldLeft(z, f) is collection_immutable.Array_FoldLeft(arr, z, f). So is a method whose signature names another generic type and that no interface needs: arr.ToList() is collection_immutable.Array_ToList(arr)..go files in its own package.Building
.go files build together with the .gala files. A plain go build or go test does not understand .gala sources. Build with gala or Bazel.martianoff/gala/... or transpile .gala files. A Go module built without GALA depends on go.gala.fyi/stdlib and on libraries written with gala export (Part 5). go.gala.fyi/stdlib and martianoff/gala are different packages and do not mix.x.gen.go next to x.gala (or x_test.gen_test.go next to x_test.gala). That is the name gala build gives the .gala file’s output, so the clash is an error.gala_deps (Part 4).gala.mod, Go modules, and Bazel integrationTry, Option and Either, the types Go results becomeGALA-Exxxx diagnostic named in this guide