Go language supports ordinary functions, anonymous functions and closures. The functions have been optimized and improved from the design to make the functions more convenient to use. In the Go language, the func keyword is used to define a function, and the syntax is "func function name (parameter) (return value) {function body}"; after defining the function, we can call the function through "function name ()".
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
Function is an organized, reusable code segment used to implement a single or related function, which can improve the modularity of the application and the reuse rate of the code.
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.
The functions of the Go language belong to "first-class citizens" (first-class), that is to say:
The function itself can be passed as a value.
Supports anonymous functions and closures.
Function can satisfy the interface.
Function definition
The func
keyword is used to define functions in Go language. The specific format is as follows:
func 函数名(参数)(返回值){ 函数体 }
Among them:
- Function name: composed of letters, numbers, and underscores. But the first letter of the function name cannot be a number. Within the same package, function names cannot have the same name (see the concept of packages later).
- Parameters: Parameters consist of parameter variables and types of parameter variables. Use
,
to separate multiple parameters. - Return value: The return value consists of the return value variable and its variable type. You can also just write the type of the return value. Multiple return values must be wrapped with
()
and,
separated. - Function body: a code block that implements the specified function.
Let’s first define a function that finds the sum of two numbers:
func intSum(x int, y int) int { return x + y }
The parameters and return value of the function are optional. For example, we can implement a function that neither A function with no parameters and no return value:
func sayHello() { fmt.Println("Hello 沙河") }
Call of function
After defining the function, we can passfunction name()
method calls the function. For example, when we call the two functions defined above, the code is as follows:
func main() { sayHello() ret := intSum(10, 20) fmt.Println(ret) }
Note that when calling a function with a return value, you do not need to receive its return value.
Parameters
##Type abbreviation
If the adjacent variables in the parameters of the function have the same type, the type can be omitted, for example:
func intSum(x, y int) int { return x + y }In the above code, the
intSum function has two parameters. The types are all
int, so the type of
x can be omitted, because there is a type description after
y, and the
x parameter is also of this type.
Variable parameters
Variable parameters means that the number of parameters of the function is not fixed. Variable parameters in the Go language are identified by adding... after the parameter name.
func intSum2(x ...int) int { fmt.Println(x) //x是一个切片 sum := 0 for _, v := range x { sum = sum + v } return sum }Call the above function:
ret1 := intSum2() ret2 := intSum2(10) ret3 := intSum2(10, 20) ret4 := intSum2(10, 20, 30) fmt.Println(ret1, ret2, ret3, ret4) //0 10 30 60When fixed parameters are used with variable parameters, the variable parameters should be placed after the fixed parameters, example The code is as follows:
func intSum3(x int, y ...int) int { fmt.Println(x, y) sum := x for _, v := range y { sum = sum + v } return sum }Call the above function:
ret5 := intSum3(100) ret6 := intSum3(100, 10) ret7 := intSum3(100, 10, 20) ret8 := intSum3(100, 10, 20, 30) fmt.Println(ret5, ret6, ret7, ret8) //100 110 130 160Essentially, the variable parameters of the function are implemented through slicing.
Function return value
In Go language, the return value is output through the
return keyword.
Multiple return values
Function in Go language supports multiple return values. If the function has multiple return values, you must use()Wrap all return values.
func calc(x, y int) (int, int) { sum := x + y sub := x - y return sum, sub }
Return value naming
You can name the return value when defining the function, and use these variables directly in the function body , and finally return through thereturn keyword.
func calc(x, y int) (sum, sub int) { sum = x + y sub = x - y return }
Return value supplement
When one of our function return value types is slice, nil can be regarded as a valid slice, there is no need to explicitly return a slice of length 0.func someFunc(x string) []int { if x == "" { return nil // 没必要返回[]int{} } ... }
Variable scope
##Global variable
Global variables are variables defined outside the function, which are valid throughout the entire running cycle of the program. Global variables can be accessed within functions.
package main import "fmt" //定义全局变量num var num int64 = 10 func testGlobalVar() { fmt.Printf("num=%d\n", num) //函数中可以访问全局变量num } func main() { testGlobalVar() //num=10 }Local variables
Local variables are divided into two types: Variables defined within a function cannot be used outside the function. For example, the following sample code cannot be used in the main function. Use the variable x defined in the testLocalVar function:
func testLocalVar() { //定义一个函数局部变量x,仅在该函数内生效 var x int64 = 100 fmt.Printf("x=%d\n", x) } func main() { testLocalVar() fmt.Println(x) // 此时无法使用变量x }
If the local variable and the global variable have the same name, the local variable is accessed first.
package main import "fmt" //定义全局变量num var num int64 = 10 func testNum() { num := 100 fmt.Printf("num=%d\n", num) // 函数中优先使用局部变量 } func main() { testNum() // num=100 }
接下来我们来看一下语句块定义的变量,通常我们会在if条件判断、for循环、switch语句上使用这种定义变量的方式。
func testLocalVar2(x, y int) { fmt.Println(x, y) //函数的参数也是只在本函数中生效 if x > 0 { z := 100 //变量z只在if语句块生效 fmt.Println(z) } //fmt.Println(z)//此处无法使用变量z }
还有我们之前讲过的for循环语句中定义的变量,也是只在for语句块中生效:
func testLocalVar3() { for i := 0; i <h2 id="strong-函数类型与变量-strong"><strong>函数类型与变量</strong></h2><h3 id="autoid-2-2-0"><strong></strong></h3><hr><h3 id="autoid-2-2-0"> <strong>定义函数类型</strong><br> </h3><p>我们可以使用<code>type</code>关键字来定义一个函数类型,具体格式如下:</p><pre class="brush:php;toolbar:false">type calculation func(int, int) int
上面语句定义了一个calculation
类型,它是一种函数类型,这种函数接收两个int类型的参数并且返回一个int类型的返回值。
简单来说,凡是满足这个条件的函数都是calculation类型的函数,例如下面的add和sub是calculation类型。
func add(x, y int) int { return x + y } func sub(x, y int) int { return x - y }
add和sub都能赋值给calculation类型的变量。
var c calculation c = add
函数类型变量
我们可以声明函数类型的变量并且为该变量赋值:
func main() { var c calculation // 声明一个calculation类型的变量c c = add // 把add赋值给c fmt.Printf("type of c:%T\n", c) // type of c:main.calculation fmt.Println(c(1, 2)) // 像调用add一样调用c f := add // 将函数add赋值给变量f1 fmt.Printf("type of f:%T\n", f) // type of f:func(int, int) int fmt.Println(f(10, 20)) // 像调用add一样调用f }
高阶函数
高阶函数分为函数作为参数和函数作为返回值两部分。
函数作为参数
函数可以作为参数:
func add(x, y int) int { return x + y } func calc(x, y int, op func(int, int) int) int { return op(x, y) } func main() { ret2 := calc(10, 20, add) fmt.Println(ret2) //30 }
函数作为返回值
函数也可以作为返回值:
func do(s string) (func(int, int) int, error) { switch s { case "+": return add, nil case "-": return sub, nil default: err := errors.New("无法识别的操作符") return nil, err } }
匿名函数和闭包
匿名函数
函数当然还可以作为返回值,但是在Go语言中函数内部不能再像之前那样定义函数了,只能定义匿名函数。匿名函数就是没有函数名的函数,匿名函数的定义格式如下:
func(参数)(返回值){ 函数体 }
匿名函数因为没有函数名,所以没办法像普通函数那样调用,所以匿名函数需要保存到某个变量或者作为立即执行函数:
func main() { // 将匿名函数保存到变量 add := func(x, y int) { fmt.Println(x + y) } add(10, 20) // 通过变量调用匿名函数 //自执行函数:匿名函数定义完加()直接执行 func(x, y int) { fmt.Println(x + y) }(10, 20) }
匿名函数多用于实现回调函数和闭包。
闭包
闭包指的是一个函数和与其相关的引用环境组合而成的实体。简单来说,闭包=函数+引用环境
。 首先我们来看一个例子:
func adder() func(int) int { var x int return func(y int) int { x += y return x } } func main() { var f = adder() fmt.Println(f(10)) //10 fmt.Println(f(20)) //30 fmt.Println(f(30)) //60 f1 := adder() fmt.Println(f1(40)) //40 fmt.Println(f1(50)) //90 }
变量f
是一个函数并且它引用了其外部作用域中的x
变量,此时f
就是一个闭包。 在f
的生命周期内,变量x
也一直有效。 闭包进阶示例1:
func adder2(x int) func(int) int { return func(y int) int { x += y return x } } func main() { var f = adder2(10) fmt.Println(f(10)) //20 fmt.Println(f(20)) //40 fmt.Println(f(30)) //70 f1 := adder2(20) fmt.Println(f1(40)) //60 fmt.Println(f1(50)) //110 }
闭包进阶示例2:
func makeSuffixFunc(suffix string) func(string) string { return func(name string) string { if !strings.HasSuffix(name, suffix) { return name + suffix } return name } } func main() { jpgFunc := makeSuffixFunc(".jpg") txtFunc := makeSuffixFunc(".txt") fmt.Println(jpgFunc("test")) //test.jpg fmt.Println(txtFunc("test")) //test.txt }
闭包进阶示例3:
func calc(base int) (func(int) int, func(int) int) { add := func(i int) int { base += i return base } sub := func(i int) int { base -= i return base } return add, sub } func main() { f1, f2 := calc(10) fmt.Println(f1(1), f2(2)) //11 9 fmt.Println(f1(3), f2(4)) //12 8 fmt.Println(f1(5), f2(6)) //13 7 }
闭包其实并不复杂,只要牢记闭包=函数+引用环境
。
defer语句
Go语言中的defer
语句会将其后面跟随的语句进行延迟处理。在defer
归属的函数即将返回时,将延迟处理的语句按defer
定义的逆序进行执行,也就是说,先被defer
的语句最后被执行,最后被defer
的语句,最先被执行。
举个例子:
func main() { fmt.Println("start") defer fmt.Println(1) defer fmt.Println(2) defer fmt.Println(3) fmt.Println("end") }
输出结果:
start end 3 2 1
由于defer
语句延迟调用的特性,所以defer
语句能非常方便的处理资源释放问题。比如:资源清理、文件关闭、解锁及记录时间等。
What functions does go language support?
在Go语言的函数中return
语句在底层并不是原子操作,它分为给返回值赋值和RET指令两步。而defer
语句执行的时机就在返回值赋值操作后,RET指令执行前。具体如下图所示:
defer经典案例
阅读下面的代码,写出最后的打印结果。
func f1() int { x := 5 defer func() { x++ }() return x } func f2() (x int) { defer func() { x++ }() return 5 } func f3() (y int) { x := 5 defer func() { x++ }() return x } func f4() (x int) { defer func(x int) { x++ }(x) return 5 } func main() { fmt.Println(f1()) fmt.Println(f2()) fmt.Println(f3()) fmt.Println(f4()) }
defer面试题
func calc(index string, a, b int) int { ret := a + b fmt.Println(index, a, b, ret) return ret } func main() { x := 1 y := 2 defer calc("AA", x, calc("A", x, y)) x = 10 defer calc("BB", x, calc("B", x, y)) y = 20 }
问,上面代码的输出结果是?(提示:defer注册要延迟执行的函数时该函数所有的参数都需要确定其值)
扩展知识:
内置函数介绍
内置函数 | 介绍 |
---|---|
close | 主要用来关闭channel |
len | 用来求长度,比如string、array、slice、map、channel |
new | 用来分配内存,主要用来分配值类型,比如int、struct。返回的是指针 |
make | 用来分配内存,主要用来分配引用类型,比如chan、map、slice |
append | 用来追加元素到数组、slice中 |
panic和recover | 用来做错误处理 |
panic/recover
Go语言中目前(Go1.12)是没有异常机制,但是使用panic/recover
模式来处理错误。 panic
可以在任何地方引发,但recover
只有在defer
调用的函数中有效。 首先来看一个例子:
func funcA() { fmt.Println("func A") } func funcB() { panic("panic in B") } func funcC() { fmt.Println("func C") } func main() { funcA() funcB() funcC() }
输出:
func A panic: panic in B goroutine 1 [running]: main.funcB(...) .../code/func/main.go:12 main.main() .../code/func/main.go:20 +0x98
程序运行期间funcB
中引发了panic
导致程序崩溃,异常退出了。这个时候我们就可以通过recover
将程序恢复回来,继续往后执行。
func funcA() { fmt.Println("func A") } func funcB() { defer func() { err := recover() //如果程序出出现了panic错误,可以通过recover恢复过来 if err != nil { fmt.Println("recover in B") } }() panic("panic in B") } func funcC() { fmt.Println("func C") } func main() { funcA() funcB() funcC() }
注意:
recover()
必须搭配defer
使用。defer recover
一定要在可能引发panic
的语句之前定义。
练习题
分金币
/* 你有50枚金币,需要分配给以下几个人:Matthew,Sarah,Augustus,Heidi,Emilie,Peter,Giana,Adriano,Aaron,Elizabeth。 分配规则如下: a. 名字中每包含1个'e'或'E'分1枚金币 b. 名字中每包含1个'i'或'I'分2枚金币 c. 名字中每包含1个'o'或'O'分3枚金币 d: 名字中每包含1个'u'或'U'分4枚金币 写一个程序,计算每个用户分到多少金币,以及最后剩余多少金币? 程序结构如下,请实现 ‘dispatchCoin’ 函数 */ var ( coins = 50 users = []string{ "Matthew", "Sarah", "Augustus", "Heidi", "Emilie", "Peter", "Giana", "Adriano", "Aaron", "Elizabeth", } distribution = make(map[string]int, len(users)) ) /* func main() { left := dispatchCoin() fmt.Println("剩下:", left) } */ func main() { for _, v := range users { distribution[v] = 0 for _, k := range v { if k == 'e' || k == 'E' { distribution[v]++ } if k == 'i' || k == 'I' { distribution[v] += 2 } if k == 'o' || k == 'O' { distribution[v] += 3 } if k == 'u' || k == 'U' { distribution[v] += 4 } } } pay := 0 for i, v := range distribution { fmt.Printf("%s 分到:%d\n", i, v) pay += v } fmt.Printf("剩余:%d", (coins - pay)) }
【相关推荐:Go视频教程】
The above is the detailed content of What functions does go language support?. For more information, please follow other related articles on the PHP Chinese website!

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)