Knaph

Functions

Basic functions

func add(a int, b int) int {
	return a + b
}

Parameter and return types are explicit — no inference on a function signature the way there is on a local variable. When consecutive parameters share a type, you can write it once:

func add(a, b int) int {
	return a + b
}

Multiple return values

This is the feature that shapes almost everything else about how Go code is written. A function can return more than one value, no tuple or object wrapper required:

func divide(a, b int) (int, int) {
	quotient := a / b
	remainder := a % b
	return quotient, remainder
}
 
q, r := divide(17, 5)
fmt.Println(q, r) // 3 2

You can even name the return values in the signature, which both documents them and gives you a "naked return" shorthand:

func divide(a, b int) (quotient, remainder int) {
	quotient = a / b
	remainder = a % b
	return
}

Variadic functions

A function can accept a variable number of arguments with ...:

func sum(nums ...int) int {
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}
 
sum(1, 2, 3)       // 6
sum(1, 2, 3, 4, 5) // 15

Inside the function, nums is just a slice of int — you'll meet slices properly next module. fmt.Println itself is variadic, which is why you can pass it any number of arguments of any type.

Sign in to track your progress through this course.

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.

SummarizeChatGPTClaude
Ask me questionsChatGPTClaude
Let's learn togetherChatGPTClaude