Detailed explanation of functions as values ​​and types in Golang

藏色散人
Release: 2020-11-13 13:58:49
forward
2533 people have browsed it

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!

Detailed explanation of functions as values ​​and types in GolangIntroduction

In the Go language, we can use the function as a variable and use type to define it, then this Function types can be passed as values ​​and can even implement methods. This feature is so flexible that sometimes we can even use this feature for type conversion. The conditions for passing as value are that the types have the same parameters and the same return value.

Type conversion of functions

The basic format of type conversion in Go language is as follows:
type_name(expression)
Copy after login
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    
// 我是一个函数类型    
// 我是一个函数类型
Copy after login

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
Copy after login

As shown in the above example, the f parameter type of Calculate is CalculateType, and the add and mul functions have the same parameters and return values ​​as the CalculateType function type. Therefore, the add and mul functions can be passed as parameters into the Calculate function.

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)    }
Copy after login
// HandleFunc registers the handler function for the given pattern.    func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {      mux.Handle(pattern, HandlerFunc(handler))    }
Copy after login
type HandlerFunc func(ResponseWriter, *Request)        
// ServeHTTP calls f(w, r).    
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {      f(w, r)    }
Copy after login

When I first saw this source code, I was really a little confused. The purpose of this source code is to Our Handler is forced to implement the ServeHTTP() method, as in the following example:
func sayHi(w http.ResponseWriter, r *http.Request) 
{      
io.WriteString(w, "hi")    
}        
func main() {      
http.HandlerFunc("/", sayHi)      
http.ListenAndserve(":8080", nil)    
}
Copy after login
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!

Related labels:
source:learnku.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template