4. Go Functions and Methods
Functions are the building blocks of Go programs. Go functions can return multiple values, support named return values, and can be used as closures. The language also supports variadic functions and defer statements. Understanding functions is essential for writing modular Go code. Go's approach to functions is clean and practical, emphasizing simplicity and readability.
Go doesn't have classes, but you can define methods on types using receiver functions. Methods are functions with a special receiver argument that appears between the func keyword and the method name. This allows Go to support object-oriented programming patterns without inheritance.
Basic Functions and Multiple Return Values
Go functions are declared with the func keyword, followed by the name, parameters, and return types. Go supports multiple return values, which is commonly used for returning values and errors. Named return values can be used to document the function and enable naked returns. The defer statement schedules a function call to run after the surrounding function returns.
Go functions can also be used as values, assigned to variables, and passed as arguments to other functions. This functional programming support makes Go flexible and expressive. Variadic functions can accept a variable number of arguments using the ... syntax.
package main import ( "fmt" "errors" "os" ) // Function with no parameters and no return func greet() { fmt.Println("Hello, World!") } // Function with parameters and one return func add(a int, b int) int { return a + b } // Function with same type parameters (type can be written once) func multiply(a, b int) int { return a * b } // Function returning multiple values func divide(a, b int) (int, int) { quotient := a / b remainder := a % b return quotient, remainder } // Function with named return values func calculate(a, b int) (sum int, diff int) { sum = a + b diff = a - b return // Naked return (returns sum and diff) } // Function with error handling func safeDivide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } // Function with variadic parameters func sumNumbers(nums ...int) int { total := 0 for _, n := range nums { total += n } return total } // Function returning a function (closure) func makeMultiplier(factor int) func(int) int { return func(x int) int { return x * factor } } // Function with defer (cleanup) func readFile(filename string) error { fmt.Printf("Opening file: %s ", filename) // Defer runs after the function returns defer func() { fmt.Printf("Closing file: %s ", filename) }() // Simulate error if filename == "" { return errors.New("empty filename") } fmt.Printf("Reading file: %s ", filename) return nil } // Function as a value var operation = func(a, b int) int { return a + b } func main() { greet() sum := add(5, 3) fmt.Printf("Add: %d ", sum) product := multiply(5, 3) fmt.Printf("Multiply: %d ", product) quotient, remainder := divide(10, 3) fmt.Printf("Divide: %d remainder %d ", quotient, remainder) s, d := calculate(10, 3) fmt.Printf("Sum: %d, Diff: %d ", s, d) result, err := safeDivide(10, 2) if err != nil { fmt.Printf("Error: %v ", err) } else { fmt.Printf("Safe divide: %d ", result) } total := sumNumbers(1, 2, 3, 4, 5) fmt.Printf("Sum numbers: %d ", total) multiplyBy2 := makeMultiplier(2) fmt.Printf("5 * 2 = %d ", multiplyBy2(5)) // Defer example err = readFile("data.txt") if err != nil { fmt.Printf("Error: %v ", err) } // Function as a value fmt.Printf("Operation result: %d ", operation(5, 3)) // Anonymous function (immediately invoked) func(x int) { fmt.Printf("Anonymous function: %d ", x) }(42) // Function with multiple return values and error handling if result, err := safeDivide(10, 0); err != nil { fmt.Printf("Error: %v ", err) } else { fmt.Printf("Result: %d ", result) } return }
Multiple return values are a key feature of Go, commonly used for returning results and errors. Named return values document the function and enable naked returns. Defer statements ensure cleanup code runs even when errors occur. Variadic functions (using ...) accept a variable number of arguments.
Methods on Types
Go doesn't have classes, but you can define methods on types using receiver functions. A method is a function with a special receiver argument that appears between the func keyword and the method name. The receiver can be a value or a pointer. Methods allow you to attach behavior to types and implement interfaces.
Value receivers operate on a copy of the type, while pointer receivers can modify the original type. Pointer receivers are more efficient for large structs and are required when you need to modify the receiver. Methods are a powerful way to organize code and implement object-oriented patterns in Go.
package main import ( "fmt" ) // Define a struct type Rectangle struct { Width float64 Height float64 } // Method with value receiver (doesn't modify) func (r Rectangle) Area() float64 { return r.Width * r.Height } // Method with pointer receiver (modifies) func (r *Rectangle) Scale(factor float64) { r.Width *= factor r.Height *= factor } // Method with pointer receiver for consistency func (r *Rectangle) Perimeter() float64 { return 2 * (r.Width + r.Height) } // Method with value receiver func (r Rectangle) String() string { return fmt.Sprintf("Rectangle(%.2f x %.2f)", r.Width, r.Height) } type Circle struct { Radius float64 } func (c Circle) Area() float64 { return 3.14159 * c.Radius * c.Radius } func (c Circle) String() string { return fmt.Sprintf("Circle(%.2f)", c.Radius) } // Interface type Shape interface { Area() float64 String() string } func printArea(s Shape) { fmt.Printf("Area of %s: %.2f ", s.String(), s.Area()) } func main() { rect := Rectangle{Width: 10, Height: 5} circle := Circle{Radius: 7} fmt.Printf("Rectangle area: %.2f ", rect.Area()) rect.Scale(2) fmt.Printf("After scaling: %s ", rect.String()) fmt.Printf("Perimeter: %.2f ", rect.Perimeter()) printArea(rect) printArea(circle) // Type assertion if rectShape, ok := interface{}(rect).(Rectangle); ok { fmt.Printf("Rectangle type: %+v ", rectShape) } // Using interface with pointer receiver var shape Shape = &rect printArea(shape) return }
Value receivers operate on a copy and cannot modify the original. Pointer receivers can modify the original and are more efficient for large structs. Interfaces define behavior that types can implement. Type assertions check if an interface holds a specific type.
Knowledge Check
Ready to test your understanding of 4. Go Functions and Methods?