In Go programming language, the 'func' keyword is used to declare a function type. The syntax for declaring a function type is:

type funcName func(arg1 argType1, arg2 argType2, ...) returnType

Here, 'funcName' is the name of the function type, 'arg1', 'arg2', etc. are the arguments of the function, 'argType1', 'argType2', etc. are the types of the arguments, and 'returnType' is the type of the return value.

For example, suppose we want to declare a function type for a function that takes two integers as arguments and returns a boolean value. We can declare the function type as follows:

type IntPredicate func(int, int) bool

Now, we can use this 'IntPredicate' type to declare variables or parameters that can hold or accept functions of this type. For example:

func isGreater(a, b int) bool {
    return a > b
}

func isLess(a, b int) bool {
    return a < b
}

func main() {
    var greater IntPredicate = isGreater
    var less IntPredicate = isLess

    fmt.Println(greater(5, 3)) // Output: true
    fmt.Println(less(5, 3))    // Output: false
}

In this example, we declare two functions 'isGreater' and 'isLess' that match the 'IntPredicate' type. We then declare variables 'greater' and 'less' of type 'IntPredicate' and assign the respective functions to them. Finally, we call these functions using the variables.

Golang Function Type: Defining and Using Function Signatures

原文地址: https://www.cveoy.top/t/topic/pgdx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录