search
HomeBackend DevelopmentGolangDetailed 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!

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

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

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

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

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Golang vs. C  : Code Examples and Performance AnalysisGolang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AM

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

Is technology stack convergence just a process of technology stack selection?Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PM

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.