#The function we want to implement today is: sum all the values in the map.
Non-generic function
How to implement it if there is no generic type? Because value may have different types, such as: int64, float64, etc., without generics, different types need to be implemented through different functions, so we generally implement it as follows:
func SumInts(m map[string]int64) int64 { var s int64 for _, v := range m { s += v } return s } func SumFloats(m map[string]float64) float64 { var s float64 for _, v := range m { s += v } return s }
The above Code, we have defined two functions:
1. SumInts() calculates the sum of value as int64 type; 2. SumFloats() calculates the sum of value as float64 type;
The above function only It is suitable for int64 and float64 types. If we still want to calculate int, float32, etc., we have to re-copy the above function and modify the type.
Isn’t it a little troublesome to do this, and the code is very bloated? Not to mention, there are many similar codes in the previous standard package, such as the Sort package (sort.go) of the standard library in order to implement different types of slicing. Sorting, IntSlice, Float64Slice, StringSlice are defined.
Because the previous Go version did not support generics, it can only be implemented in this way, which is also the simplest method.
With generics, how can we implement a function to calculate the sum of values for different types of int64 and float64?
Generic function
#In this section we use a generic function to receive a map whose value is int64 type as a parameter, and also Can receive a map whose value is float64 type as parameter.
The complete code is as follows:
func Sum[K comparable, V int64 | float64](m map[K]V "K comparable, V int64 | float64") V { var s V for _, v := range m { s += v } return s } func main() { ints := map[string]int64{ "first": 1, "second": 2, } fmt.Println(Sum[string, int64](ints "string, int64")) floats := map[string]float64{ "first": 35.98, "second": 26.99, } fmt.Println(Sum[string, float64](floats "string, float64")) }
In the above code, we defined the Sum() function, which is a generic function. You can see that the difference from the ordinary function is that the function name and There is a set of square brackets [] between the function parameter list. There are two parameters K and V in the square brackets. They are called type parameters in the Go language. Following K and V are type restrictions. , where comparable is pre-declared by Go language and represents any type that can perform == and != operations. The type restriction of V is one of int64 and float64. The function parameter is m, the type is map[K]V, and the return type is V.
Calling a function is also a little different from calling an ordinary function. There is a set of square brackets [] between the function name and the actual parameters, indicating the type name. For example, when the Sum() function is called for the first time, the type names are string and int64 respectively. Then when the function is executed, the corresponding types of K and V are string and int64 respectively.
第二次调用该 Sum() 函数时,K、V 的类型分别是 string 和 float64。
通过泛型编程,我们就可以实现一个函数处理多种数据类型。
执行上面的代码输出:
3 62.97
The above is the detailed content of A preliminary exploration of generics in Go1.18. For more information, please follow other related articles on the PHP Chinese website!

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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