Functions
func add(a, b number) number {
return a + b
}
func greet(name string) { // without a result type it returns nothing
console.log(`Hello, ${name}`)
}
function add(a, b) {
return a + b
}
function greet(name) {
console.log(`Hello, ${name}`)
}
Adjacent parameters of the same type can be grouped: a, b number is the same as
a number, b number.
An object type is a result when the body follows it, func origin() { x, y number } { ... }; in
parentheses, ({ x, y number }), it is one anywhere.
Default values and the rest of the arguments
func greet(name string = "you", times = 1) string {
return name.repeat(times)
}
func log(level string, ...parts any[]) {
console.log(level, ...parts)
}
greet() // "you"
log("info", "saved", 3)
- Parameters with default values come last and may be left out in a call. A default value without
a type gives the parameter its type,
times = 1, and sees the parameters before it. ...parts any[]takes the arguments after the others in an array; it is the last parameter, and each argument is checked against the type of the elements.- Both are written the same way in functions, methods, constructors,
funcliterals and arrow functions, and stay the same in JS.
Multiple results
func divmod(a, b number) (number, number) {
return Math.floor(a / b), a % b
}
const q, r = divmod(17, 5)
const _, rest = divmod(17, 5) // _ skips a value
function divmod(a, b) {
return [Math.floor(a / b), a % b]
}
const [q, r] = divmod(17, 5)
const [, rest] = divmod(17, 5)
The rules are those of Go:
- several values can only be returned with
returnand unpacked at once into variables inlet/constor in an assignment; - the number of variables must match the number of values;
divmod(17, 5) + 1is a compile error.
Anonymous functions
const square = func(x number) number { return x * x }
const sum = (a, b number) => a + b
const doubled = nums.map(x => x * 2) // the type of x comes from the context
Arrow functions are as in JS, with Go-style types. If the type of a parameter cannot be inferred from the context, it must be written.
A func literal compiles to an arrow function too, so this inside it is the this of the
surrounding method, not a new one as with function in JS.
defer
defer postpones a call until the function exits: on return, at the end of the body or on an
exception.
func readConfig(path string) (string, error) {
const fd = fs.openSync(path, "r")
defer fs.closeSync(fd)
const text = fs.readFileSync(fd, "utf8")
if text == "" {
return "", error("empty config")
}
return text, null
}
function readConfig(path) {
const fd = fs.openSync(path, 'r')
try {
const text = fs.readFileSync(fd, 'utf8')
if (text === '') {
return ['', new Error('empty config')]
}
return [text, null]
} finally {
fs.closeSync(fd)
}
}
The rules are those of Go:
- the function and its arguments are evaluated at the
defer, and the call happens on exit; - several deferred calls run in reverse order;
- if a deferred call throws, the others still run;
deferbelongs to the whole function, not to a block: adeferin a loop adds a call on every iteration, and all of them run when the function exits;deferis allowed only inside functions and methods;- inside
defer { ... }there can be noreturn, andbreakandcontinueonly in loops nested in it: deferred code cannot change how the function ended.
func countdown() {
for let i = 0; i < 3; i++ {
defer console.log(i)
}
}
// countdown() prints 2, 1, 0
For several actions there is a block form; its content runs as a whole on exit:
defer {
conn.close()
console.log("connection closed")
}
If all the defers are at the top level of the function's body, the compiler writes nested
try/finally, as in the example above. If a defer is inside an if or a loop, the deferred calls
are collected in a stack and run in finally.