Home Common Problem What is fn in go language?

What is fn in go language?

Apr 17, 2023 am 11:46 AM
golang go language

In the Go language, fn specifically refers to the keyword func. The basic components of a function are: keyword func, function name, parameter list, return value, function body and return statement. Each program contains many Function, a function is a basic block of code. A function is an organized, reusable code segment used to implement a single or related function.

What is fn in go language?

Operating system for this tutorial: Windows 10 system, GO version 1.20, Dell G3 computer

Go language function declaration (function definition )

Functions are organized, reusable code segments used to implement single or related functions, which can improve application modularity and code reuse. Go language supports ordinary functions, anonymous functions and closures. The functions are optimized and improved from the design to make the functions more convenient to use.

Functions constitute the logical structure of code execution. In Go language, the basic components of functions are: keyword func, function name, parameter list, return value, function body and return statement. Each program contains There are many functions, and functions are basic blocks of code.

Because the Go language is a compiled language, the order in which the functions are written is irrelevant. In view of the readability requirements, it is best to write the main() function at the front of the file, and other functions follow the Write in a certain logical order (such as the order in which functions are called).

The main purpose of writing multiple functions is to decompose a complex problem that requires many lines of code into a series of simple tasks to solve. Moreover, the same task (function) can be called multiple times, which helps Code reuse (in fact, good programs pay great attention to the DRY principle, that is, Don't Repeat Yourself (Don't Repeat Yourself), which means that the code that performs a specific task can only appear once in the program).

The function will exit when it reaches the last line of the code block or before the return statement. The return statement can have zero or more parameters. These parameters will be used as return values ​​for the caller. Simple The return statement can also be used to end the infinite loop of for, or end a coroutine (goroutine).

Go language functions do not need to be declared

Go language functions are first-class citizens. Like variables, they can be assigned to a certain variable (the reason for the emergence of anonymous functions)

Since functions are first-class citizens, all the formats used to define variables in the past can be used to define variables of function type

    var 变量名称 函数类型
    var 变量名称 函数类型 = 匿名函数
    var 变量名称  = 匿名函数
    变量名称  := 匿名函数
    var(
        var 变量名称  = 匿名函数
    )
Copy after login
fn = func (a,b int){
    return a + b
}
fn()
Copy after login

The way to define function variables in Go language is different from that in C language

Format: func function name (parameter list) return value list{}

The function return value in Go language can be more than one

func test(a,b int) (a,b int){
    return a,b
}
Copy after login

Go language function return value can be only Write type, you can also write variable type

Write-only type: func test(a,b int) (int){} Note: Write-only type, the parentheses on both sides of the return value type int can be omitted

Variable plus type: func test(a,b int) (a,b int){}
Note: When writing the variable type form, return does not need to add a return value, and it will automatically find a in the code block If the type of Go language formal parameter list or return value list is the same as b

func test(a,b int) (a,b int){
      a = 100
      b = 99
      return //自动返回100,99}
Copy after login

, then we can continuously define
as follows: two functions represent the same method

func test(a,b int) (a,b int){return a,b}
func test2(a int,b int) (int,int){return a,b}
Copy after login

Since the Go language function There can be multiple return values, so when the external function receives multiple return values, it needs to use multiple variables to receive them. However, if variables are not used in Go language, an error will be reported, so if we have a return value that does not need to be used, we will use _ to receive, _ has a specific meaning in the Go language, so it cannot be used as an identifier for a variable

Anonymous function

Anonymous function is a function without a name. It needs to be used immediately after being defined otherwise an error will be reported

Anonymous functions are usually only used once. Since they are first-class citizens, they can be used as formal parameters of the function or as the return value of the function

As a function Formal parameters

fn  := func (a,b int) int {
  return a + b
}

//此时调用test函数用来计算a+b可以这么写
res := test(a,b,fn)

func test(a,b int,method func(int,int) int) func() {
  return method(a,b)
}
Copy after login

Further evolution

Since fn and are anonymous function assignments, we can directly pass the anonymous function into test

//此时调用test函数用来计算a+b可以这么写
res := test(a,b,func (a,b int) int {
  return a + b
})

func test(a,b int,method func(int,int) int) func() {
  return method(a,b)
}
Copy after login

as the return value of the function

fn := test()
fn()//打印匿名函数

func test() func() {
    return func() {
        fmt.Println("匿名函数")
    }
}
Copy after login

Closure (special anonymous function)

If external variables are used in the returned anonymous function, it is called a closure

Characteristics of closure: "People are in "As long as external variables are used in the returned anonymous function, if the anonymous function is still used after the function call, the function stack will not be released. Once it is no longer used, the function stack will be released.

fn := test()//test函数也被称为迭代器
fn()  //2
fn()  //3
fn()  //4

func test() func(){
     x := 1
     return func (){
            x++
            println(x)
        }
}
Copy after login

Memory performance of anonymous functions

What is fn in go language?

Illustration

  1. The code area stores the codes of three functions, corresponding to one address

  2. Define the variable fn and pass the address of the anonymous function to fn

  3. ##Call the function test to open up storage space

  4. Open storage space for num, value, method, res, where method saves the address of the function passed to it

  5. Execute the function, method saves the address of the anonymous function, When the method is executed, the storage space is opened and the values ​​​​of a and b are stored. After the function ends, the value is returned to res and the storage space of the method is released.

  6. Res is printed, the test function is also released, and fn is also released after use

The above is the detailed content of What is fn 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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 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. �...

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...

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, ...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

How to ensure concurrency is safe and efficient when writing multi-process logs? How to ensure concurrency is safe and efficient when writing multi-process logs? Apr 02, 2025 pm 03:51 PM

Efficiently handle concurrency security issues in multi-process log writing. Multiple processes write the same log file at the same time. How to ensure concurrency is safe and efficient? This is a...