Skip to content

Functions

TypeScript functions are flexible — arrow functions, default params, rest params, tuple returns. Go functions are more explicit but similarly powerful. The main surprise for TypeScript developers: Go functions can return multiple values natively, without wrapping in a tuple or array.

TypeScript
function add(a: number, b: number): number {
return a + b;
}
// Arrow function
const greet = (name: string): string => {
return `Hello, ${name}!`;
};
Go
func add(a int, b int) int {
return a + b
}
// No arrow functions — just func
func greet(name string) string {
return "Hello, " + name + "!"
}

In TypeScript, returning two things means a tuple or an object. In Go, multiple returns are a first-class feature used everywhere — especially for returning a result alongside an error.

TypeScript
// TypeScript: tuple or object
function divide(a: number, b: number): [number, Error | null] {
if (b === 0) return [0, new Error("division by zero")];
return [a / b, null];
}
const [result, err] = divide(10, 2);
Go
// Go: multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
result, err := divide(10, 2)

Go variadics work exactly like TypeScript rest parameters. Use ...T in the parameter list; inside the function it’s a slice.

TypeScript
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4);
Go
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
sum(1, 2, 3, 4)
package main
import (
"errors"
"fmt"
)
func add(a, b int) int {
return a + b
}
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println(add(3, 4))
result, err := divide(10, 3)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("10 / 3 = %.4f\n", result)
}
fmt.Println(sum(1, 2, 3, 4, 5))
}
How does Go handle returning multiple values from a function?
What syntax declares a variadic parameter in Go?
In Go, what keyword defines a function?
When can you use the := short declaration?