If you have any questions or suggestions, please contact us in time. My official account is “Brain fried Fish”, GitHub address: github.com/eddycjy.

Hello, I’m fried fish.

In Go, when it comes to functions, people often mention that “Go functions are first-class citizens”. This definition comes out of the blue, so let’s first understand what first-class citizenship is.

According to Wikipedia’s definition of first-class citizen:

In programming language design, a first-class citizen (also type, object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, modified, and assigned to a variable.

In programming language design, a first-class citizen of a given programming language (that is, a type, object, entity, or value) can assign a function to a variable or use the function as an argument or return value to another function.

The functions of the Go language also meet this definition and are often referred to as “first-class citizens.” Now that we know the background, let’s expand further.

Common function

In Go, normal functions are defined in the format func [function name](input parameter)(output parameter), as follows:

Func callFuncA(x, y string) (s string, err error) {return x + y, nil} func main() {callFuncA(" fried ", "fried fish ")}Copy the code

In the sample code, you declare a method called callFuncA, which is only allowed to be called inside the package, so the first letter is lowercase.

It has two inputs, x and y, both of type String. The outgoing parameters are the variables S and err, of type string and error, respectively.

In addition, when returning a value inside a function, you can also use a quick return mode:

func callFuncA(x, y string) (s string, err error) {
	s = x + y
	return
}
Copy the code

The name of a variable declared as an argument can be applied to its own function. Therefore, a direct return implicitly returns the declared exit argument.

When a function is defined, its input arguments also support mutable syntax:

func callFuncA(x ... String) (s string, err Error) {s = strings.join (x, ",") return} func main() {FMT.Println(callFuncA(" fried "," fried "))}Copy the code

Declare x on the entry variable… String indicates that x is a variable of type string and can be passed multiple string arguments.

The variable is passed in the form of a slice, which we’ll cover in a later section. You can think of it as a dynamic array of unlimited length:

[0: fried 1: fried fish]Copy the code

In general, the common follow-up operations of variable variables are cyclic traversal processing, or splicing and other operations.

Anonymous functions

The Go language also supports anonymous function declarations by default, in much the same way as normal functions:

Func main() {s := func(x, y string) (s string, err error) {return x + y, nil} s(" ", "")}Copy the code

Anonymous functions can be declared anywhere and do not require a function name. If the function body is immediately followed by (), the function is executed immediately after the declaration:

Func main() {s, _ := func(x, y string) (s string, err error) {return x + y, nil}Copy the code

In all use of function classes, it is important to understand the scope of function variables:

Func main() {x, y := func() (s string, err error) {return x + y, nil}() FMT.Println(s)}Copy the code

This anonymous function has no parameters and no corresponding variables are defined inside the function. At this time, it reads the values of global x and Y variables and the output result is “fried fish”.

Func main() {x, y := func(x, y string) (s string, err error) {x = "y" return x + y, nil}(x, y) {x, y := func(x, y string) (s string, err error) {x = "y" return x + y, nil}(x, y) y) fmt.Println(x, y) }Copy the code

This anonymous function takes a parameter, but reassigns the variable x inside the function. So what is the final value of the external variable x? The output is “fried fish.”

Why doesn’t the value of the global variable x change even though it has been reassigned inside the function?

The essential reason is that the scope is different, and the variable x modified inside the function is a local variable inside the function. External variables are global and belong to different scopes.

Structure method

In the form of a combined structure (struct), methods belonging to the structure can be declared:

type T struct{} func NewT() *T { return &T{} } func (t *T) callFuncA(x, y string) (s string, err error) { return x + y, Nil} func main() {NewT().callfunca (" fried ", "fried fish ")}Copy the code

Specific functions are used in the same way as ordinary functions.

Structure-related value passing and reference-passing method calls are covered in a later section.

Built-in function

The Go language has built-in support for functions that can be called without reference to a third-party standard library. The built-in functions are designed to work with the regular use of the Go language, and there are very few of them. As follows:

  • Used to get the length and capacity of certain types: len, cap.
  • Used to create and allocate certain types of memory: new, make.
  • Used for error handling mechanisms (exception panic, exception catching) : Panic, recover.
  • Used for copying and adding slices: copy, append.
  • For simple output information: print, println.
  • For complex numbers: complex, real, imag.

We will expand on the actual usage scenarios of each built-in function in subsequent chapters, because each built-in function corresponds to each type of usage scenario by nature.

conclusion

In this chapter, we introduce why the function of Go language is called first-class citizen, and give a basic explanation for all kinds of deformation of function: ordinary function, anonymous function, structural method and built-in function.

In the face of the novice most prone to make mistakes in the function scope problem, also carried out a basic comb. This piece of advice we should think deeply, understand, to avoid stepping on pit in the future.

My official account

Share Go language, micro service architecture and strange system design, welcome to pay attention to my public number and I exchange and communication.

The best relationship is mutual achievement. Your praise is the biggest motivation for the creation of fried fish. Thank you for your support.