Classes
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
}
}
private,protectedandpublic(the default) are checked only by the compiler, as in TypeScript. They do not get into JS, so JS code can reach the fields.- Visibility is set by modifiers, not by the case of the first letter as in Go.
- Fields are reached through
thisinside methods, as in JS. - Methods can return several values.
- A field without a value gets the zero value of its type. If the type has none (a class, an interface, a function), the field must be assigned in the constructor.
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
- Getters and setters are written as in JS,
get name() Tandset name(v T), and compile to the same. They make one member of the class: it is read and assigned as a field,c.area. A getter takes nothing and returns one value, a setter takes one value; when both are declared, they have one type. A getter alone cannot be assigned, a setter alone cannot be read. - A field and an accessor of a base class do not override each other: in JS a field is set on each instance and would hide the getter of the prototype, so a getter where the base has a field, or a field where it has a getter, is an error.
readonlyfields are assigned only by their value or in the constructor of their class,this.center = center, as in TypeScript. Like visibility, it is checked by the compiler only and does not get into JS.
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
- An abstract class has no instances of its own:
new Shape()is an error, and its subclasses make them. It is an ordinary class in JS. - An abstract method has no body; it does not get into JS. A class that is not abstract
implements the abstract methods of its bases, and only an abstract class declares them.
Getters and setters can be abstract too,
abstract get name() string, fields cannot. - An abstract method is not
private, which the subclasses that implement it could not see, norstatic, andsuper.area()cannot call it. abstractis a name elsewhere: a keyword only beforeclassand in a class.
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.
- Its fields are data, as the arguments of
goare: numbers, strings, arrays, objects of interfaces, other data classes, channels. A field of a function type is a compile error; methods are the class's, not the instance's, so they are fine. - It extends only a data class, whose fields go with it; a subclass is marked too,
data class Admin extends User, and one that is not is an ordinary class, whose instances cannot go to a goroutine. A data class cannot extend a class of JS. - How: the module registers the class with the runtime,
$$dataClass(Point, id), with an id of its name and a hash of its code, the same in the module and in its worker module, which has a copy of the class. The thread that sends lists the instances in the copy, and the one that gets it gives them their class again (Object.setPrototypeOf). The worker module has the data classes of its module and imports those of other modules, also those used there only as types. - Not to other tabs: a topic is a compile error for a data class, since another tab may not have its code; send an object of an interface.
datais a name elsewhere: it is a keyword only beforeclass.