Home Backend Development Golang What is the method of defining anonymous functions in go language?

What is the method of defining anonymous functions in go language?

Jan 06, 2023 pm 07:37 PM
golang go language anonymous function

The anonymous function definition method in the Go language is "func (parameter list) (return parameter list) {function body}". In fact, the definition of an anonymous function is an ordinary function definition without a name. An anonymous function can be completely regarded as a type, can be assigned directly, can be assigned to a variable, can be used as an actual parameter or return value, and of course can also be called directly.

What is the method of defining anonymous functions in go language?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Go language supports anonymous functions, that is, you define a function when you need to use it. Anonymous functions do not have function names, only function bodies. Functions can be assigned to variables of function type as a type. Anonymous functions are often also named Passed in the form of variables, this is similar to the callback function in C language. The difference is that Go language supports defining anonymous functions in the code at any time.

Anonymous function refers to a function implementation method that does not require the definition of a function name. It consists of a function declaration and a function body without a function name. The following is an introduction to how to define an anonymous function.

Define an anonymous function

The definition format of an anonymous function is as follows:

func(参数列表)(返回参数列表){
    函数体
}
Copy after login

The definition of an anonymous function has no name Ordinary function definition.

Basic usage

Anonymous function can be regarded as a type, can be directly assigned, can be assigned to variables, and can be used as actual parameters Or return the value for use, of course you can also call it directly

1) Call the anonymous function when defining

Anonymous functions can be called after declaration, for example:

func(data int) {
    fmt.Println("hello", data)
}(100)
Copy after login

Note the (100) after the } in line 3, indicating that the anonymous function is called and the parameter passed is 100.

2) Assign anonymous functions to variables

Anonymous functions can be assigned values, for example:

// 将匿名函数体保存到f()中
f := func(data int) {
    fmt.Println("hello", data)
}
// 使用f()调用
f(100)
Copy after login

Anonymous functions are very versatile and themselves It is a value that can be easily stored in various containers to implement callback functions and operation encapsulation.

Where to use anonymous functions

Callback function

Why use callback function? , let’s analyze it. A is the main function, and B is passed to the main function as a parameter. We can see from the above example that when we define the main function, we only define the parameters and return value type of function B. Then as long as the function B satisfies the type we defined and can be processed by function A, so using the callback function can make our main function more versatile. In layman's terms, the main function provides an interface, and any function that conforms to the rules of this interface can be used.

type Callback func(a, b int) int

// 提供接口,外部随便怎么搞,只要符合规则就行
func api(x,y int, callback Callback) int {
    return callback(x, y)
}

// 回调函数,只要满足传入参数类型为int
// 并且返回值类型也是int就都可以
func add(a, b int) int {
    return a + b
}
Copy after login

Closure

What is a closure? A closure is an entity composed of a function and its related reference environment.

func add() func(int) int {
    var b int
    return func(a int) int {
        b = b + a
        return b
    }
}

var f = add()
Copy after login

Here f is a closure, f saves a reference to b. Simply put, there is a pointer in f pointing to the address of b, so we can get the following results

fmt.Println(f(1)) // 由于b初始化为0,所以输出1
fmt.Println(f(2)) // 由于上一行代码已经修改了b的值,所以输出4
Copy after login

So Speaking of closure is equivalent to using anonymous functions inside our functions to handle all things related to variables

[Related recommendations: Go video tutorial, Programming teaching]

The above is the detailed content of What is the method of defining anonymous functions in go language?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 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.

How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? Apr 02, 2025 pm 02:15 PM

Automatic deletion of Golang generic function type constraints in VSCode Users may encounter a strange problem when writing Golang code using VSCode. when...

See all articles