Go Functions
A function is a named block of code that performs a specific task. Functions allow code to be written once and reused many times. They make programs easier to read, test, and maintain.
Declaring a Function
package main
import "fmt"
func greet(name string) {
fmt.Println("Hello,", name)
}
func main() {
greet("Alice")
greet("Bob")
}
Output:
Hello, Alice
Hello, Bob
Function Anatomy Diagram
func greet (name string) string {
│ │ │ │
│ │ │ └── return type (optional)
│ │ └─────────────── parameter: name with type string
│ └────────────────────────── function name
└───────────────────────────────── keyword to declare function
// function body
return "Hello, " + name
}
Function with Return Value
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
result := add(10, 5)
fmt.Println(result) // 15
}
Function with Shortened Parameter Types
When multiple parameters share the same type, the type only needs to be written once at the end.
func multiply(a, b int) int {
return a * b
}
Named Return Values
Return values can be named in the function signature. The function then uses a bare return without listing the values again.
package main
import "fmt"
func divide(a, b float64) (result float64, err string) {
if b == 0 {
err = "cannot divide by zero"
return
}
result = a / b
return
}
func main() {
r, e := divide(10, 2)
fmt.Println(r, e) // 5 (empty string)
r2, e2 := divide(10, 0)
fmt.Println(r2, e2) // 0 cannot divide by zero
}
Functions as Values
Functions in Go are first-class values. They can be stored in variables and passed to other functions.
package main
import "fmt"
func square(n int) int {
return n * n
}
func main() {
fn := square // store function in a variable
fmt.Println(fn(4)) // 16
}
Key Points
- Functions are declared with
func, a name, parameters, and return type - Parameters with the same type can share one type declaration
- Named return values allow a bare
returnat the end of the function - Functions are values — they can be assigned to variables or passed as arguments
