Home >Backend Development >Golang >Detailed explanation of functions as values and types in Golang
The following tutorial column will introduce you to functions as values and types in Golang. I hope it will be helpful to friends in need!
Introduction
Type conversion of functions
type_name(expression)For example:
package main import "fmt" type CalculateType func(int, int) // 声明了一个函数类型 // 该函数类型实现了一个方法 func (c *CalculateType) Serve() { fmt.Println("我是一个函数类型") } // 加法函数 func add(a, b int) { fmt.Println(a + b) } // 乘法函数 func mul(a, b int) { fmt.Println(a * b) } func main() { a := CalculateType(add) // 将add函数强制转换成CalculateType类型 b := CalculateType(mul) // 将mul函数强制转换成CalculateType类型 a(2, 3) b(2, 3) a.Serve() b.Serve() } // 5 // 6 // 我是一个函数类型 // 我是一个函数类型
As above , declares a CalculateType function type, implements the Serve() method, and casts add and mul with the same parameters into the CalculateType function type. At the same time, both functions have the Serve() method of the CalculateType function type.
Function parameter transfer
package main import "fmt" type CalculateType func(a, b int) int // 声明了一个函数类型 // 加法函数 func add(a, b int) int { return a + b } // 乘法函数 func mul(a, b int) int { return a * b } func Calculate(a, b int, f CalculateType) int { return f(a, b) } func main() { a, b := 2, 3 fmt.Println(Calculate(a, b, add)) fmt.Println(Calculate(a, b, mul)) } // 5 // 6
net/http package source code example
// HandleFunc registers the handler function for the given pattern // in the DefaultServeMux. // The documentation for ServeMux explains how patterns are matched. func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { DefaultServeMux.HandleFunc(pattern, handler) }
// HandleFunc registers the handler function for the given pattern. func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { mux.Handle(pattern, HandlerFunc(handler)) }
type HandlerFunc func(ResponseWriter, *Request) // ServeHTTP calls f(w, r). func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r) }
func sayHi(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hi") } func main() { http.HandlerFunc("/", sayHi) http.ListenAndserve(":8080", nil) }Because HandlerFunc is a function type, and the sayHi function has the same parameter value as the HandlerFunc function type, so sayHi can be forced to be converted to HandlerFunc, so sayHi also has the ServeHTTP() method, which implements the Handler interface. At the same time, the ServeHTTP method of HandlerFunc executes itself, which is the sayHi function. This can be seen. sayHi is the execution result after the Handler is called. .
The above is the detailed content of Detailed explanation of functions as values and types in Golang. For more information, please follow other related articles on the PHP Chinese website!