Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Summary of functional basic Syntax and Advanced Features of go language

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the "functional basic syntax and advanced feature summary of go language". In daily operation, I believe that many people have doubts about the functional basic syntax and advanced feature summary of go language. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "functional basic syntax and advanced feature summary of go language". Next, please follow the editor to study!

Biologists and mathematicians have different positions.

Although it is the same world, different people look at things from their own standpoints, and the results are naturally different.

Biologists subconsciously classify animals and plants, and so do object-oriented programming, using a series of abstract models to simulate the behavior of the real world.

Mathematicians have always been famous for their rigorous study. As the most important basic science, mathematical laws and inductive deductive methodology correspond to functional programming, which is more likely to create laws instead of simulating reality.

Standard functional programming has a strong mathematical color, but fortunately, Go is not a functional language, so there is no need to be limited by almost exacting rules.

To put it simply, functional programming has the following characteristics:

Immutability: no state variables and mutable objects

A function can only have one argument

Pure functions have no side effects.

There is a passage from Wikipedia about functional programming:

In computer science, functional programming is a programming paradigm-a style of building the structure and elements of computer programs-that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

Functional programming regards computer programs as deductions of mathematical functions and does not use state variables or variable objects to express the relationship between numbers.

For more information, click to visit Wikipedia's introduction to functional programming Functional programming.

The foothold and starting point of functional programming is function, and complex function is formed by certain combination law of basic function, so the process of describing complex function is how to disassemble and reassemble.

So next, while reviewing, we learn the basic characteristics of functions, laying the foundation for the next understanding of functional programming. About the basic language of functions, please refer to the basic grammar of go Learning Notes which are worthy of special attention.

Basic syntax and advanced features of functions

The following four basic operations as an example, throughout the full text to explain the basic grammar and advanced features of the function, and strive to know why.

Func defines ordinary functions

The eval function defines the basic operation rules of addition, subtraction, multiplication and division. If the operation type is not supported, an exception is thrown and the program is terminated.

Func eval (a, b int, op string) int {var result int switch op {case "+": result = a + b case "-": result = a-b case "*": result = a * b case "/": result = a / b default: panic ("unsupported operator:" + op)} return result}

When the test does not define the operation to take the remainder, an exception is thrown, unsupported operator:%, indicating that only the basic operation of addition, subtraction, multiplication and division is supported.

Func TestEval (t * testing.T) {/ / 3-120 unsupported operator:% t.Log (eval (1,2, "+"), eval (1,2, "-"), eval (1,2, "*"), eval (1,2, "/"), eval (1,2, "%"),)}

Multiple return values define standard functions

The obvious difference between Go and other mainstream programming languages is that functions support multiple return values, usually the first return value represents the real result, and the second return value indicates whether it is wrong or not, which is also the unique feature of Go about exception error design.

If it returns normally, it means that there is no error, then the first return value is the normal result and the second return value is empty nil;. If the exception returns, the first return value is designed with a meaningless special value, and the second return value is a specific error message, which is generally not nil.

Func evalWithStandardStyle (a, b int, op string) (int, error) {switch op {case "+": return a + b, nil case "-": return a-b, nil case "*": return a * b, nil case "/": return a / b, nil default: return 0, fmt.Errorf ("unsupported operator:% s", op)}}

The eval function is modified to write a real Go program, which is tested again at this time, and the results show that when there is no defined operator, the exception is no longer thrown, but the default zero value is returned and a short error description is given.

Func TestEvalWithStandardStyle (t * testing.T) {/ / Success: 2 if result, err: = evalWithStandardStyle (5,2, "/"); err! = nil {t.Log ("Error:", err)} else {t.Log ("Success:", result)} / / Error: unsupported operator:% if result, err: = evalWithStandardStyle (5,2, "%") Err! = nil {t.Log ("Error:", err)} else {t.Log ("Success:", result)}}

Other functions are passed in as parameters

The above example solves the problem that an unsupported operator will report an error to terminate the program through multiple return values, but it does not really solve the problem. If you really want to do a non-predefined operation, there is nothing you can do!

Who told you to be a user, not a designer?

Then the stage is up to you, you are the protagonist, you can handle the input and output as you want, and all the logic is transferred to the user, so that there is no situation in which the demand can not be met.

Func evalWithApplyStyle (a, b int, op func (int, int) (int, error)) (int, error) {return op (a, b)}

The operator is changed from the original string string to the function func (int, int) (int, error), the stage is left to you, it all depends on free play!

The function parameter op is called directly inside the evalWithApplyStyle function and the processing result of the function is returned. In the current demonstration example, the control of the function is completely transferred to the function input parameter op function. The actual situation can decide how to deal with the evalWithApplyStyle logic according to the actual needs.

Func divide (a, b int) (int, error) {return a / b, nil} func mod (a, b int) (int, error) {return a% b, nil}

Do-it-yourself, adequate food and clothing, easily define division divide and take the remainder mod operation, and then test the results.

Func TestEvalWithApplyStyle (t * testing.T) {/ / Success: 2 if result, err: = evalWithApplyStyle (5,2, divide); err! = nil {t.Log ("Error:", err)} else {t.Log ("Success:", result)} / / Success: 1 if result, err: = evalWithApplyStyle (5,2, mod) Err! = nil {t.Log ("Error:", err)} else {t.Log ("Success:", result)}}

The test result is very ideal, not only to achieve the basic operations such as subtraction, addition, multiplication and division, but also to achieve the remainder operation which has not been possible before!

This shows that this kind of function as a parameter fully arouses the enthusiasm of the working people, and my mother no longer has to worry that I won't be able to achieve complex functions.

Anonymous functions can also be used as parameters

Generally speaking, when calling a function, it is called directly with the function name, and the individual function is reusable, but if it is an one-time function, it is not necessary to define a function with a function name.

Still the above example, this time the operation rules for two numbers are no longer mathematical operations, this time we will compare the maximum values of two numbers and implement them in the form of anonymous functions.

Func TestEvalWithApplyStyle (t * testing.T) {/ / Success: 5 if result, err: = evalWithApplyStyle (5,2, func (an int, b int) (result int, e error) {if a > b {return a, nil} return b, nil}); err! = nil {t.Log ("Error:", err)} else {t.Log ("Success:", result)}}

The return value of a function can be a function

Still the above example, if, for some reason, you do not need to return the calculation result of the function immediately, but wait for the user to calculate the return value when the time is right, then the function return value is still a function, which is the so-called lazy evaluation.

Func evalWithFunctionalStyle (a, b int, op func (int, int) (int, error)) func () (int, error) {return func () (int, error) {return op (a, b)}}

The above function may seem a little difficult to understand, but in fact, it only changes the return value relative to the above example, from the original (int, error) to func () (int, error), and the rest remains the same!

The evalWithFunctionalStyle function is still the user's home field, and the only difference compared with the above example is that your home court is up to you, and when the referee is completely in charge, it is not necessary to announce the result immediately after running it.

Func pow (a, b int) (int, error) {return int (math.Pow (float64 (a), float64 (b)), nil} func TestEvalWithFunctionalStyle (t * testing.T) {ef: = evalWithFunctionalStyle (5,2, pow) time.Sleep (time.Second * 1) / / Success: 25 if result, err: = ef () Err! = nil {t.Log ("Error:", err)} else {t.Log ("Success:", result)}}

Time.Sleep (time.Second * 1) demo code means that after executing the evalWithFunctionalStyle function, the final result can not be calculated immediately, and when the time is right, the user calls the ef () function again for lazy evaluation.

/ / 1 1 2 3 5 8 13 21 34 55 int / a b int / a bfunc fibonacci () int () int {a, b: = 0,1 return func () int {a, b = b, int a}}

Function can act as a type

The above example shows that the function can be used as a return value, the parameter has a function, and the return value also has parameters, so the evalWithFunctionalStyle function looks more laborious, and the type alias of the Go language is born for simplification, not to mention that the function is a first-class citizen in Go, of course.

Func evalWithFunctionalStyle (a, b int, op func (int, int) (int, error)) func () (int, error) {return func () (int, error) {return op (a, b)}}

So we intend to unify the input parameter function func (int, int) (int, error) and the return value function func () (int, error). The only difference between the input parameter function and the return value function is that the number of input parameters is different, so it is reasonable to think of the syntax related to the variable length parameters in the Go function.

Type generateIntFunc func (base... int) (int, error)

In this way, both the input function and the output function can be replaced by the generateIntFunc type function, and then the evalWithFunctionalStyle function can be modified.

Func evalWithObjectiveStyle (a, b int, op generateIntFunc) generateIntFunc {return func (base... int) (I int, e error) {return op (a, b)}}

The modified evalWithObjectiveStyle function looks more concise, but it's hard to say whether it is in use in the fancy shelf, so let's talk with test cases.

Func TestEvalWithObjectiveStyle (t * testing.T) {ef: = evalWithObjectiveStyle (5,2, func (base... int) (int,error) {result: = 0 for I: = range base {result + = base [I]} return result,nil}) time.Sleep (time.Second * 1) / / Success: 7 if result, err: = ef () Err! = nil {t.Log ("Error:", err)} else {t.Log ("Success:", result)}}

Function aliases after typing does not affect the function, is still functional programming, but mixed with some object-oriented flavor.

Typed functions can implement interfaces

Functions can be typed in the form of aliases to implement interfaces, which to some extent can be regarded as a type, so it is only natural to implement interfaces.

Func (g generateIntFunc) String () string {rMagne _: = g () return fmt.Sprint (r)}

The implementation of the String interface method for the typed function generateIntFunc in the sample code here may not have much practical significance, but is only cobbled together to explain this knowledge point, the actual situation will certainly be different.

Func TestEvalWithInterfaceStyle (t * testing.T) {ef: = evalWithObjectiveStyle (5,2, func (base... int) (int,error) {result: = 0 for I: = range base {result + = base [I]} return result,nil}) time.Sleep (time.Second * 1) / / String: 7 t.Log ("String:", ef.String ()) / / Success: 7 if result Err: = ef () Err! = nil {t.Log ("Error:", err)} else {t.Log ("Success:", result)}}

The function variable ef obtained by lazy evaluation can call the String method at this time, that is, it has the ability of objectification, and the final result is the same as running the function directly?

It's a little magical. I still don't understand what this operation is. If the bosses of Go language don't hesitate to give us some advice, I would appreciate it.

A natural closure

The parameters and return values of the function can all be other functions, and the function can also be passed to the variable as a reference, and there are also simplified forms such as anonymous functions, in addition, the typed function can also be used to implement interfaces and other characteristics should be enough to explain the noble status of first-class citizens, right?

Such a powerful functional feature, as long as a little combination will have a strong ability, and Go language is not a strict functional language, there are not many grammatical restrictions.

/ / 1 1 2 3 5 8 13 21 34 55 int / a b int / a bfunc fibonacci () int () int {a, b: = 0,1 return func () int {a, b = b, int a}}

The return value of the Fibonacci sequence function fibonacci is the real generator function, and each call generates a new Fibonacci number.

This is a simple example of implementing closures in Go. The variable of the fibonacci function itself, called by the internal anonymous function func () int, is referenced, and this reference will eventually be called by the user again and again. As long as the generator continues to be called, the number of the Pei Bonacci sequence will continue to increase.

/ / 1 1 2 3 5 8 13 21 34 55func TestFibonacci (t * testing.T) {f: = fibonacci () for I: = 0; I < 10; iTunes + {fmt.Print (f (), ")} fmt.Println ()} func TestFibonacci (t * testing.T) {f: = fibonacci () for I: = 0; I < 10 ITunes + {fmt.Print (f (), ")} fmt.Println ()}

Summary of introductory functions for functional programming

A function is a first-class citizen, where function parameters, variables, and function return values can all be functions.

Higher-order functions are a combination of ordinary functions, and parameters and return values can be other functions.

Function is the foundation of functional programming, which supports functional programming but is not a functional language.

There is no pure functional programming rules, more flexible and free, good readability.

At this point, the study of "functional basic syntax and advanced features summary of go language" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report