Functions in Go
What is a function?
A function is a reusable block of code that performs a specific task.
It helps you organize logic, avoid repetition, and improve readability.
func functionName(parameters) returnType {
// code
}
func add(a int, b int) int { // Notice that the type comes after the variable name.
return a + b
}
When two or more consecutive named function parameters share a type, you can omit the type from all but the last.
func add(a, b int) int {
return a + b
}
In many languages (like C++ or Java), a function can only return one thing. If you want to return multiple things, you have to pack them awkwardly into an array or an object.
// Notice the (string, bool) at the end. That means this returns TWO things!
func checkServerHealth(serverID int) (string, bool) {
// In a real app, we'd check the database here
statusMsg := "Server is healthy"
isOnline := true
return statusMsg, isOnline
}
func main() {
// We catch the two returned values using two variables!
msg, online := checkServerHealth(101)
fmt.Println(msg, "Online:", online)
}
Named return values
In Go, return values can be named in the function signature. These names act as variables that are automatically initialized at the start of the function.
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
func main() {
fmt.Println(split(17))
}
Key points:
xandyare declared as part of the function signature- They are available throughout the function body
A return statement without arguments returns the named return values (x and y in this case). This is known as a naked return.
Anonymous Functions (Closures)
Sometimes, you need a function so briefly that it doesn't even deserve a name. Go lets you create functions inside other functions and assign them to variables, or even run them immediately.
func main() {
// We are assigning a function to a variable!
greet := func(name string) {
fmt.Println("Hello,", name)
}
// Now we can use it
greet("Cloud Engineer")
}