Classes

Rook — 1.0 specification

Classes as in JS and TypeScript, with Go-style types. Methods are declared without func, like methods of JS classes.

class User {
    name string
    private age number             // the zero value: 0
    tags string[]                  // the zero value: []
    static count = 0

    constructor(name string, age number) {
        this.name = name
        this.age = age
        User.count++
    }

    greet() string {
        return `Hi, I'm ${this.name}`
    }

    isAdult() bool {
        return this.age >= 18
    }
}

class Admin extends User {
    protected level number

    constructor(name string, age, level number) {
        super(name, age)
        this.level = level
    }

    greet() string {
        return `${super.greet()} (admin)`
    }
}

const ann = new User("Ann", 30)
class User {
  name = ''
  age = 0
  tags = []
  static count = 0

  constructor(name, age) {
    this.name = name
    this.age = age
    User.count++
  }

  greet() {
    return `Hi, I'm ${this.name}`
  }

  isAdult() {
    return this.age >= 18
  }
}

Getters, setters and readonly fields

Experimental: may change between releases; see the status at the top.

class Circle {
    readonly center Point
    private r number

    constructor(center Point, r number) {
        this.center = center
        this.r = r
    }

    get area() number {
        return Math.PI * this.r ** 2
    }

    set area(value number) {
        this.r = Math.sqrt(value / Math.PI)
    }

    get diameter() number {
        return this.r * 2
    }
}

c.area = 10                                // the setter
c.diameter = 4                             // an error: a getter without a setter
c.center = origin                          // an error: readonly

Properties of constructor parameters

Experimental: may change between releases; see the status at the top.

A parameter of a constructor with public, protected, private or readonly is a field too, which the constructor assigns first, as in TypeScript:

class User {
    constructor(readonly id string, private name string) { }
}
class User {
  constructor(id, name) {
    this.id = id
    this.name = name
  }
}

In a derived class the fields are assigned right after super(...). readonly alone makes a public field; elsewhere than in a constructor the modifiers are an error.

Abstract classes

Experimental: may change between releases; see the status at the top.

abstract class Shape {
    abstract area() number

    describe() string {
        return `area: ${this.area()}`
    }
}

class Square extends Shape {
    constructor(private side number) {
        super()
    }

    area() number {
        return this.side ** 2
    }
}

const s Shape = new Square(2)              // new Shape() is an error

Structures

Use struct for data that goroutines share. Totals{} initializes a named structure before its first thread crossing. A structure has fields and methods, including async methods. The anonymous expression struct{ ... } accepts fields, initializers written with :, and methods. A local anonymous structure captured by go or go for can also share its fields. For supported instance methods, the compiler emits a worker factory and passes ordinary external captures as copies through $$go. The receiver's fields remain shared. See Structures for channel examples and supported method captures.

Scalar int accepts safe JavaScript integers and int32 accepts integers from −2³¹ through 2³¹−1. Both are JavaScript numbers. Literal arguments are checked by the compiler. For a dynamic number, use value as int or value as int32. The conversion throws RangeError outside the range. Use a checked assignment such as x = (x + 1) as int when arithmetic may leave the range. int32[] still uses JavaScript Int32Array.

export struct Totals {
    private count = 0
    private sum = 0
    private mu rwMutex

    async add(value number) {
        await mu.mute()
        defer mu.unmute()
        count++
        sum += value
    }

    async snapshot() string {
        await mu.readMute()
        defer mu.readUnmute()
        return Struct.toString(this)
    }
}

async func accumulate(totals Totals, batch number[]) {
    for value in batch {
        await totals.add(value)
    }
}

const totals = Totals{}
const first = go accumulate(totals, [10, 20])
const second = go accumulate(totals, [30, 40])
await Promise.all([first, second])
console.log(await totals.snapshot())

After ordinary name lookup, a structure or class method can refer to an instance field without this. Use this.count to select the field when names overlap. The compiler checks private, and the field retains its ordinary JS name. Other modules can initialize public fields in a literal.

export struct Totals also exports a function under the same name in JS. Totals({}) creates a new local instance. The TypeScript declaration contains the instance type and the factory signature. Re-exports carry both. Structure guide

A postfix update can appear in an index, as in items[count++] = item. For a local structure array, make(Product[], 25) starts with length zero and requests initial capacity. The JavaScript engine controls the reserved storage.

A structure creates a fresh unlocked rwMutex, rMutex, or wMutex when its initializer omits the field. Use mute() and unmute() for a write lock, or readMute() and readUnmute() for a read lock. Put the release in a defer after successful acquisition. A synchronous acquisition fails immediately if the lock is busy. In an async function or method, await mu.mute() or await mu.readMute() waits for its turn.

rwMutex.read and rwMutex.write expose the same lock as an rMutex and wMutex, respectively. Both types use mute() and unmute(), with await lock.mute() for an acquisition that may wait. make(rMutex) creates an independent lock that multiple readers can hold. make(wMutex) creates an independent exclusive lock. Use views of the same rwMutex when readers and writers need to coordinate access to one resource.

The predeclared Struct object converts named and anonymous structures. Struct.toObject(value) copies the data into an ordinary JS object, recursively copying nested structures, plain objects and arrays. It omits inherited methods and rwMutex fields. Struct.toString(value) represents these data as compact JSON, writes bigints as strings such as "10n", and marks cycles as "[Circular]".

Shared structures in goroutines

The behavior described here is stable in 1.x. See the structure guide for how the current compiler and runtime represent shared structures.

A named structure automatically becomes shared when it first crosses a named go call as a direct argument or as its sole result. Existing references to that structure see its changes. If the function returns the argument it received, the caller gets the same instance. Use await go to wait for the updates to finish.

Supported fields include numbers, UTF-8 strings, booleans, string literal unions, dense arrays, and nested records of those fields. The named structure factories must be in scope. In go for, the elements of an ordinary structure array become shared. A replacement through the loop index is written back when the corresponding chunk finishes.

The runtime synchronizes each individual read or write. Acquire the shared rwMutex for a compound operation such as adding a product and changing its count. A synchronous acquisition of a busy lock throws. In an async method, use await mu.mute() or await mu.readMute(). The lock must be free when an instance first becomes shared.

Structures that stay in one thread need no codec or shared memory. If SharedArrayBuffer is unavailable, the runtime emits a WARNING once and runs operations on those structures in their owning thread. Function literals also share structures passed directly or captured from local scope. A typed structure channel passed through go can carry shared handles to the same instances. See Structures.

data class

Experimental: may change between releases; see the status at the top.

data class Point {
    x, y number

    constructor(x, y number) {
        this.x = x
        this.y = y
    }

    length() number {
        return Math.hypot(this.x, this.y)
    }
}

func far(p Point) bool {
    return p.length() > 10             // the copy in the worker has the methods
}

const ok = await go far(new Point(6, 8))
class Point {
  // ...
}
$$dataClass(Point, 'Point:5d1f0a2c')

A goroutine gets copies of its arguments, and a copy made by postMessage has the data of a value but not its class. data class marks a class whose instances go to other threads with their class: as arguments and results of go, through channels, inside arrays and objects.

Markdown source on GitHub