Home > Article > Backend Development > Common design patterns for golang functions
Go language function design patterns are used to improve code readability, maintainability and reusability, including: Input/output parameters: Allow functions to modify the value of the caller through parameters. Return multiple values: Simplify the code and avoid using global variables. Functions as parameters: Create flexible, customizable code.
This article introduces common function design patterns in the Go language, which can improve the readability of the code. , maintainability and reusability.
Input/output parameters allow the function to modify the value of the caller through parameters. For example, we can exchange the order of two values in the function:
func swap(a, b *int) { *a, *b = *b, *a }
Practical case: Auxiliary function for sorting:
func sort(arr []int) { for i := 0; i < len(arr); i++ { for j := i + 1; j < len(arr); j++ { if arr[i] > arr[j] { swap(&arr[i], &arr[j]) } } } }
Go language allows functions to return multiple values. This simplifies the code and avoids the use of global variables. For example, we can use the function to get the minimum and maximum values from an array:
func minMax(arr []int) (int, int) { min := arr[0] max := arr[0] for _, v := range arr { if v < min { min = v } if v > max { max = v } } return min, max }
Practical case: Function for calculating statistics:
func stats(arr []int) (float64, float64) { sum := 0 for _, v := range arr { sum += v } average := float64(sum) / float64(len(arr)) return average, float64(minMax(arr)[0] + minMax(arr)[1]) / 2 }
Go functions can be passed as parameters to other functions. This allows us to create flexible, customizable code. For example, we can use a function as a comparator function:
type Person struct { Name string Age int } func compareByName(a, b Person) int { return strings.Compare(a.Name, b.Name) } func sortByName(people []Person) { sort.Slice(people, func(i, j int) bool { return compareByName(people[i], people[j]) < 0 }) }
Practical example: Universal sorting function for slicing structures according to different fields:
func sortBy(slice interface{}, less func(i, j interface{}) bool) { sort.Slice(slice, func(i, j int) bool { return less(slice[i], slice[j]) }) }
The above is the detailed content of Common design patterns for golang functions. For more information, please follow other related articles on the PHP Chinese website!