1
If you have any questions or suggestions, please communicate and collide in time. is [Fried fish in the brain], GitHub address: 160a349daec641 https://github.com/eddycjy .

Hello everyone, I am fried fish.

In the Go language, when it comes to functions, what everyone mentions most is "Go language functions are first-class citizens". This definition came very suddenly. Let us first understand what a first-class citizen is.

According to the definition of First-class citizen in Wikipedia:

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, first-class citizens (that is, types, objects, entities, or values) in a given programming language can assign functions to variables, or use functions directly as parameters or return values of other functions.

The functions of the Go language also satisfy this definition, so they are often called "first-class citizens". After understanding the background, we will proceed further.

Ordinary function

The definition format of ordinary functions in Go language is 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("炸", "煎鱼")
}

In the sample code, callFuncA is declared. It is only allowed to be called in the package, so the first letter is lowercase.

It has two x parameters, 060a349daec76f and y , and the type is string . s parameters are the variables 060a349daec773 and err , and the types are string and error respectively.

In addition, when returning a value in the function body, you can also use a shortcut return method:

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

The variable name declared at the time of parameter output can be applied to its own function. Therefore, if 060a349daec7ab is executed directly, the return will be implicitly returned.

When the function is defined, its input parameters also support the syntax of variable parameters:

func callFuncA(x ...string) (s string, err error) {
    s = strings.Join(x, ",")
    return
}

func main() {
    fmt.Println(callFuncA("炸", "煎鱼"))
}

x ...string on the input parameter means that the variable x is a variable variable of type string string parameter.

The format passed in by a variable variable is a slice type. This type will be explained in a later chapter. You can understand it as a dynamic array with no length limitation:

[0: 炸 1: 煎鱼]

Generally, common follow-up operations on variable variables are mostly loop traversal processing, or operations such as splicing.

Anonymous function

Go language also supports the declaration of anonymous functions by default, and the way of declaration is almost the same as that of ordinary functions:

func main() {
    s := func(x, y string) (s string, err error) {
        return x + y, nil
    }

    s("炸", "煎鱼")
}

Anonymous functions can be declared anywhere, and there is no need to define the function name. If the function body is immediately followed by () it means that it will be executed immediately after the declaration:

func main() {
    s, _ := func(x, y string) (s string, err error) {
        return x + y, nil
    }("炸", "煎鱼")
}

In the use of all function classes, one thing is very important, that is, the understanding of the scope of function variables:

func main() {
    x, y := "炸", "煎鱼"
    s, _ := func() (s string, err error) {
        return x + y, nil
    }()
    fmt.Println(s)
}

The anonymous function has no formal parameters and no corresponding variables are defined inside the function. At this time, it reads x and y variables, and the output result is "fried fish".

func main() {
    x, y := "炸", "煎鱼"
    _, _ = func(x, y string) (s string, err error) {
        x = "吃"
        return x + y, nil
    }(x, y)
    fmt.Println(x, y)
}

x parameters, but the variable 060a349daec90d is reassigned inside the function. So what is the value of the variable x The output result is "fried fried fish".

Why is it that the variable x has been reassigned in the function, but the value of the x is still not changed?

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

Structure method

In the way of combining a structure (struct), you can declare the methods that belong to the structure:

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("炸", "煎鱼")
}

The usage of specific functions is the same as that of ordinary functions, and there is no other difference.

The value transfer and reference transfer method calls related to the structure will be expanded in later chapters.

Built-in function

The Go language itself supports some built-in functions, and the invocation of these built-in functions does not need to reference a third-party standard library. The purpose of built-in functions is to cooperate with the regular use of the Go language, and the number is very small. as follows:

  • Used to obtain certain types of length and capacity: len, cap.
  • Used to create and allocate certain types of memory: new, make.
  • Used for error handling mechanisms (abnormal panic, abnormal capture): panic, recover.
  • Used to copy and add slices: copy, append.
  • Used for simple output information: print, println.
  • Used to handle complex numbers: complex, real, imag.

For the real usage scenarios of each built-in function, we will further expand it in the subsequent chapters, because each built-in function essentially corresponds to various types of usage scenarios.

to sum up

In this chapter, we introduce why Go language functions are called first-class citizens, and provide basic explanations for various types of functions: ordinary functions, anonymous functions, structural methods, and built-in functions.

Faced with the problem of function scope, which is the most error-prone for beginners, I also carried out a basic sorting out. This section suggests that everyone should think and understand more deeply to avoid stepping on pits in the future.

My official account

Share Go language, microservice architecture and strange system design. Welcome everyone to follow my official account to communicate and communicate with me.

best relationship is mutual achievement , everybody thumbs is fried fish maximum power of creation, thanks for the support.


煎鱼
8.4k 声望12.8k 粉丝