Home  >  Article  >  Backend Development  >  Common design patterns for golang functions

Common design patterns for golang functions

PHPz
PHPzOriginal
2024-04-26 17:51:01482browse

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.

Common design patterns for golang functions

Common design patterns in Go language functions

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

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])
            }
        }
    }
}

Return multiple values

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
}

Function as parameter

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn