Functions
Functions: familiar ground
Section titled “Functions: familiar ground”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.
Basic function syntax
Section titled “Basic function syntax”function add(a: number, b: number): number { return a + b;}
// Arrow functionconst greet = (name: string): string => { return `Hello, ${name}!`;};func add(a int, b int) int { return a + b}
// No arrow functions — just funcfunc greet(name string) string { return "Hello, " + name + "!"}Multiple return values
Section titled “Multiple return values”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: tuple or objectfunction 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: multiple return valuesfunc 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)Variadic functions
Section titled “Variadic functions”Go variadics work exactly like TypeScript rest parameters. Use ...T in the parameter list; inside the function it’s a slice.
function sum(...nums: number[]): number { return nums.reduce((a, b) => a + b, 0);}sum(1, 2, 3, 4);func sum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total}sum(1, 2, 3, 4)Try it
Section titled “Try it”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))}Loading Go runtime (first run only, ~8 MB)…