search
HomeBackend DevelopmentGolangAn article to help you understand the basic functions of Go language (Part 2)

Last Main Review

We know from the above that when defining a function, the function memory allocation can be understood as follows.

An article to help you understand the basic functions of Go language (Part 2)

At the same time, we also know that no matter what operation is performed, it will only operate the stack The above is worth .


Functions and variables

The function name is the variable

I don’t know if you have ever thought about defining a variable and receiving a function, just like this.

package main


import "fmt"


func say() {
    fmt.Println("say")
}


func main() {
    var s1 = say
    s1()
}

The execution results are as follows.

An article to help you understand the basic functions of Go language (Part 2)

It can be found that through a variable receives a Function name, there is no problem when executing it through variable name brackets .

So, what type is this variable? ? ?

fmt.Printf("%T\n",s1)

执行结果

An article to help you understand the basic functions of Go language (Part 2)

如果我将say函数改一下呢?

func say(s int) int{
    fmt.Println("say")
    return 1
}
fmt.Printf("%T\n",s1)

An article to help you understand the basic functions of Go language (Part 2)

可以发现,如果函数参数返回值不一样,打印出来的类型也是不一样的。

定义函数类型

上述我们知道,可以通过变量接收一个函数名

通过变量接收函数名没有约束的,不管函数几个参数,几个返回值,都可以接收,真是活出了动态语言的样子。

定义函数类型就是限制变量接收函数,只能接收指定格式函数

主要用到type关键字。

格式

type 变量名 func([参数类型,参数类型]) [返回值类型]
中括号表示可选参数

例如

type a func()
type b func(int)
type a func(int,int) int

具体代码

package main


import "fmt"


/*
    定义一个函数类型的变量
    接收的函数参数必须是两个int类型
    函数的返回值也必须是int类型
*/
type cType func(int, int) int


func say1(a, b int) int {
    fmt.Println("say",a+b)
    return 1
}
func say2(a, b int) {
    fmt.Println("say")


}
func main() {
    var s1 cType
    s1 = say1//调用s1其实调用的就是say1
    s1(1,1)


    //var s2 cType
    //s2 = say2//报错,cannot use say2 (type func(int, int)) as type cType in assignment
}

高阶函数

千万不要被这个名字唬住了。

简单点说,高阶函数就是把函数当作参数或者把函数当作返回值

函数当作参数

package main


import "fmt"


func add(x int, y int) int {
    return x + y
}
func calc(x int, y int, other func(int, int) int) int {
    return other(x, y)
}
func main() {
    //将add函数传入第三个参数
    var result = calc(34, 12, add)
    fmt.Println(result)
}

函数当作返回值

package main


import "fmt"


func add(x int, y int) int {
  return x + y
}
func test() (func(int, int) int) {
  return add
}
func main() {
  var a = test()
  fmt.Println(a(1,2))
}

至于上述两个的功能,恕小生不才,至今用到的场景不多。

匿名函数

匿名函数顾名思义,就是没有名字的函数。

语法如下

func([参数,参数...])[(返回值,返回值)]{
  代码
}()
//匿名函数后面必须跟括号,直接执行

例如

func()  {
    
}()
func(x int, y int) (int) {
  return x + y
}()

代码

package main


import "fmt"


func main() {
    //s1等于一个匿名函数,并且直接执行
  var s1 = func(x int, y int) (int) {
    return x + y
  }(1,2)
  fmt.Println(s1)
}

闭包

闭包,这个有点不太理解,简单点说就是函数里面套了一个函数里面函数引用的外面函数变量

示例

package main


import "fmt"


func other() func() {
    //返回的是一个函数类型
  var a = 666
  return func() {
        //内部函数使用的是外面函数的a
    fmt.Println(a)
  }
}
func main() {
  var o = other()
  o()
}

执行结果。

An article to help you understand the basic functions of Go language (Part 2)

结果是没有问题的。

虽然我们以前学过,函数执行完毕后,里面的变量会回收。

But when using closures, it can be understood that if the inner function uses the variable of the outer function, then the variable will not be recycled.


##Summary

This article mainly talks about Functions and variables,Higher-order functions,Anonymous functions, Closure, Among them, closure is more difficult to understand, so you must spend some time on it. The edge of a sword comes from sharpening, and the fragrance of plum blossoms comes from the bitter cold. You must practice more.

The above is the detailed content of An article to help you understand the basic functions of Go language (Part 2). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment