Detailed explanation of custom function types in Golang

In Golang, the type keyword is used to define a custom type, and a function is also a data type, so the type keyword can be used to define a function type.

Define Function Type Syntax

The syntax for defining a function type is as follows:

type FuncType func(argument_list) return_type

FuncType is the defined function type name, argument_list is the parameter list of the function, and return_type is the return value type of the function. After defining a function type, you can use this type to declare variables, as function parameters or return value types, etc. A simple example is as follows:

type MathFunc func(int, int) int   // 定义函数类型

func add(x, y int) int {           // 定义加法函数
    return x + y
}

func sub(x, y int) int {           // 定义减法函数
    return x - y
}

A function type can define its own method. The following defines a method to execute the function itself

type MathFunc func(int, int) int   // 定义函数类型

func (f *MathFunc) run(str string)  {	// MathFunc 提供的方法
	fmt.Println(str)
}

func add(x, y int) int {           // 定义加法函数
    return x + y
}

func sub(x, y int) int {           // 定义减法函数
    return x - y
}

Complete usage example

Here is a complete usage example:

package main

import "fmt"

type MathFunc func(int, int) int   // 定义函数类型

func (f *MathFunc) test(str string) { // MathFunc 提供的方法
	fmt.Println(str)
}

func add(x, y int) int {           // 定义加法函数
    return x + y
}

func sub(x, y int) int {           // 定义减法函数
    return x - y
}

func main() {
    var f MathFunc      // 声明函数类型变量
    f = add             // 函数类型变量赋值为加法函数
    fmt.Println(f(1, 2))// 给加法函数传参并打印返回值
  	f.test("路多辛的博客")
    f = sub             // 函数类型变量赋值为减法函数
    fmt.Println(f(3, 2))// 给减法函数传参并打印返回值
  	f.test("路多辛的所思所想")
}

Run to see the effect

$ go run main.go
3
路多辛的博客
1
路多辛的所思所想

First, a function type named MathFunc is defined, which is used to describe a function that accepts two int type parameters and returns a value of int type, and defines a test method, and then implements two specific functions: add and sub. A function is bound to a function type variable f, and f is called by passing different parameters to perform addition or subtraction.

important point

There are a few things to keep in mind when using custom function types:

  • The signature of the custom function type needs to be consistent with the signature of the actual function, otherwise a compilation error will occur;
  • Custom function types can be assigned, passed parameters, etc. like other types;
  • A custom function type can be used as a function parameter or return value type.

summary

In Golang, functions are first-class citizens that can be passed as function parameters or returned as function return values. By using a custom function type, the use of functions can be more flexible.

Guess you like

Origin blog.csdn.net/luduoyuan/article/details/131406037