当前位置:网站首页>[introduction to go language] 11 go language functions
[introduction to go language] 11 go language functions
2022-07-16 06:47:00 【Space time traveler er】
List of articles
11 Go Language functions
11.1 Function declaration and call
Function declaration
A program instruction to perform a function ( sentence ) Set , Called a function .
Go The language standard library provides a variety of built-in functions that can be used . for example ,len() Functions can take different types of arguments and return the length of that type .
Syntax of function declaration :
func function_name ([parameter_list]) [return_list] {
The body of the function
}
Syntax description :
- func - Function is defined by func Keyword start
- function_name - Name of function
- parameter_list - parameter list , The parameter list is used to specify the parameter type 、 The order 、 And the number of parameters . When a function is called , You can pass values to parameters , This value is called the actual parameter . Function name and parameter list together constitute function signature . The parameter list is optional .
- return_list - Return value list , Used to specify the function return value and its data type .Go Language functions can have multiple return values . Some functions do not need return values , There is no need for return_list.
- The body of the function - Function defined code set .
Example ( Function definition ):
/* Function returns the maximum of two numbers */
func max(num1, num2 int) int {
/* Declare local variables */
var result int
if (num1 > num2) {
result = num1
} else {
result = num2
}
return result
}
Function call
Use function calls to execute the code in the function body .
Call function , Pass parameter values to the function , After function execution , Return value .
Example ( Call function max):
package main
import "fmt"
func main() {
var a int = 100
var b int = 200
var ret int
/* Call the function and return the maximum value */
ret = max(a, b)
fmt.Printf( " The maximum is : %d\n", ret )
}
/* Function returns the maximum of two numbers */
func max(num1, num2 int) int {
/* Defining local variables */
var result int
if (num1 > num2) {
result = num1
} else {
result = num2
}
return result
}
Built-in functions
Go The language predefines some functions , You can use them without referencing any packages , Here are all the built-in functions :
- close be used for channel Communications . Use it to close channel.
- delete Used in map Delete instance in .
- len and cap Can be used for different types of values ,len Used to return a string 、 Length of slices and arrays .cap The capacity used to return slices .
- new For various types of memory allocation .
- make For built-in types (map、slice、channel) Memory allocation .
- copy Used to copy slices
- append Used to append slices .
- panic and recover For exception handling mechanism .
- print and println Is the underlying print function , Can be introduced without fmt Package is used . They are mainly used for debugging .
- complex、real and imag All used to deal with complex numbers .
11.2 Function parameter
Indefinite parameter function
Indefinite parameter means that the number of formal parameters of a function is indefinite , To do this , First, you need to define a function to accept an indefinite number of parameters :
package main
import "fmt"
func dynamicParameter(args ...int) int {
sum := 0
for _, arg := range args {
sum += arg
}
return sum
}
func main() {
fmt.Println(dynamicParameter(1, 2, 3, 4))
fmt.Println(dynamicParameter(1, 2, 3, 4, 5))
}
Form like ...type The data type of format can only exist as the parameter type of function , And it must be the last parameter .
It's a grammar sugar .Go The compiler will package the actual parameters passed in as an array slice and pass it to the formal parameter . Array slicing will be introduced in subsequent lessons .
Any type of indefinite parameter
In the previous example, the type of the indefinite parameter is specified as int, If you want to pass any type , You can specify the type as interface{}. Here is Go In the language standard library fmt.Printf() Function prototype of :
func Printf(format stirng, args ...interface{
}) {
// ...
}
use interface{} Passing any type of data is Go Management usage of language .
Example (MyPrintf):
package main
import "fmt"
func MyPrintf(args ...interface{
}) {
for _, arg := range args {
switch arg.(type) {
case int:
fmt.Println(arg, "is an int value.")
case string:
fmt.Println(arg, "is a string value.")
case int64:
fmt.Println(arg, "is an int64 value.")
default:
fmt.Println(arg, "is an unknown type.")
}
}
}
func main() {
var v1 int = 1
var v2 int64 = 234
var v3 string = "hello"
var v4 float32 = 1.234
MyPrintf(v1, v2, v3, v4)
}
11.3 Function return value
Multiple return values
Go Can return multiple values , for example :
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("Hello", "World")
fmt.Println(a, b) // Output World Hello
}
Name the return value
Go The return value of function supports naming , The return value after naming is equivalent to the local variable in the function , and Go The language initializes them with a zero value .
func cal(n1 int, n2 int) (sum int, sub int) {
sum = n1 + n2
sub = n1 - n2
return // Function will return sum and sub
}
11.4 How to pass parameters
If you use parameters when defining a function , Then the variables in the parameter list are called formal parameters .
Formal parameters are like local variables defined inside the body of a function .
When you call a function , There are two ways to pass parameters :
| Delivery type | describe |
|---|---|
| Value passed | Value passing refers to passing a copy of the actual parameter to the function when it is called , In this way, if the parameter is modified in the function , Will not affect the actual parameters . |
| reference | Reference passing refers to passing the address of the actual parameter to the function when the function is called , So the changes to the parameters in the function , It will affect the actual parameters . |
Value passed
Passing refers to copying the actual parameters into the function when calling the function , In this way, if the parameter is modified in the function , Will not affect the actual parameters .
By default ,Go Language uses value passing , That is, the actual parameters will not be affected during the call .
As defined below swap() function :
/* Define functions that exchange values with each other */
func swap(x, y int) int {
var temp int
temp = x /* preservation x Value */
x = y /* take y Value is assigned to x */
y = temp /* take temp Value is assigned to y*/
return temp;
}
Next , Let's use value passing to call swap() function :
package main
import "fmt"
func main() {
/* Defining local variables */
var a int = 100
var b int = 200
fmt.Printf(" Exchange before a The value of is : %d\n", a )
fmt.Printf(" Exchange before b The value of is : %d\n", b )
/* Exchange values by calling functions */
swap(a, b)
fmt.Printf(" After exchanging a Value : %d\n", a )
fmt.Printf(" After exchanging b Value : %d\n", b )
}
/* Define functions that exchange values with each other */
func swap(x, y int) int {
var temp int
temp = x /* preservation x Value */
x = y /* take y Value is assigned to x */
y = temp /* take temp Value is assigned to y*/
return temp;
}
The execution result is :
Exchange before a The value of is : 100
Exchange before b The value of is : 200
After exchanging a Value : 100
After exchanging b Value : 200
Value passing is used in the program , So the two values do not interact , We can use the reference passing described later to achieve the exchange effect .
Pointer passing
Pointer passing refers to passing the address of the actual parameter to the function when calling the function , So the changes to the parameters in the function , It will affect the actual parameters .
Here's the exchange function swap() , Pointer passing is used :
/* Define exchange value function */
func swap(x *int, y *int) {
var temp int
temp = *x /* keep x The value on the address */
*x = *y /* take y Value is assigned to x */
*y = temp /* take temp Value is assigned to y */
}
Here we use pointer passing to call swap() function :
package main
import "fmt"
func main() {
/* Defining local variables */
var a int = 100
var b int= 200
fmt.Printf(" Exchange before ,a Value : %d\n", a )
fmt.Printf(" Exchange before ,b Value : %d\n", b )
/* call swap() function * &a Point to a The pointer ,a The address of the variable * &b Point to b The pointer ,b The address of the variable */
swap(&a, &b)
fmt.Printf(" After exchanging ,a Value : %d\n", a )
fmt.Printf(" After exchanging ,b Value : %d\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x /* preservation x The value on the address */
*x = *y /* take y Value is assigned to x */
*y = temp /* take temp Value is assigned to y */
}
The execution result of the above code is :
Exchange before ,a Value : 100
Exchange before ,b Value : 200
After exchanging ,a Value : 200
After exchanging ,b Value : 100
11.5 Anonymous functions
Anonymous functions
Function name is not specified when defining function . There are two forms :
Call directly when defining anonymous functions :
func main() { res := func(n1 int, n2 int) int { return n1 + n2 }(10, 20) fmt.Println(res) }Assign an anonymous function to a variable , Then call the function through the variable name :
func main() { a := func(n1 int, n2 int) int { return n1 - n2 } res := a(10, 30) }
Closure
The concept of closures : A closure is an entity composed of a function and its related reference environment .
Go Language anonymous functions can be used to implement closures : When an anonymous function references a variable defined outside the function, it becomes a closure .
In the following example , We created the function getSequence() , Return another function . The purpose of this function is to increment... In the closure i Variable , The code is as follows :
package main
import "fmt"
func getSequence() func() int {
i:=0
return func() int {
i+=1
return i
}
}
func main(){
/* nextNumber For a function , function i by 0 */
nextNumber := getSequence()
/* call nextNumber function ,i Variable self increasing 1 And back to */
fmt.Println(nextNumber())
fmt.Println(nextNumber())
fmt.Println(nextNumber())
/* Create a new function nextNumber1, And look at the results */
nextNumber1 := getSequence()
fmt.Println(nextNumber1())
fmt.Println(nextNumber1())
}
The execution result of the above code is :
1
2
3
1
2
Example 2:
package main
import "fmt"
func getSequence() (func() int, func() int) {
i := 0
return func() int {
i += 1
return i
}, func() int {
i += 2
return i
}
}
func main() {
nextNumber1, nextNumber2 := getSequence()
fmt.Println(nextNumber1())
fmt.Println(nextNumber2())
fmt.Println(nextNumber1())
fmt.Println(nextNumber2())
fmt.Println(nextNumber1())
fmt.Println(nextNumber2())
}
// Execution results
// 1
// 3
// 4
// 6
// 7
// 9
11.6 Deferred function call
defer sentence
Go Language passing defer Statement to add the code executed at the end of the function , It is often used to release some allocated resources 、 Close database connection 、 To break off socket、 Unlock a locked resource .Go The language guarantees that the function will be executed after it is finished defer Code in statement .
defer Statement in function return After statement 、 Execute before returning the caller function . Here's an example :
package main
import "fmt"
func main() {
myFunction()
fmt.Println("after myFunction")
}
func myFunction() {
fmt.Println("enter myFuntion")
defer func() {
fmt.Println("in defer")
}()
fmt.Println("myFunction return")
return
}
// The above program output
// enter myFuntion
// myFunction return
// in defer
// after myFunction
Multiple defer The order in which statements are executed
When there are multiple defer When the sentence is , Execute in reverse order as they add ( LIFO mode ), Example :
func main() {
myFunction()
}
func myFunction() {
for i:=0; i < 5; i++ {
defer fmt.Printf("%d ", i)
}
}
// The above program output
// 4 3 2 1 0
边栏推荐
猜你喜欢

第十二届蓝桥杯嵌入式模拟题

How to make electronic signature transparent

Distributed theory

蓝桥杯嵌入式-HAL库-TIM_BASE

pyopencv基础操作指南

Friendly zeropi uboot, kernel compilation,

如何将电子签名透明化处理

C language bit operation (applicable to the operation of MCU registers)

Virtual memory location structure (reserved area, code area, stack area, heap area, literal constant area) and variable modifiers (const, auto, static, register, volatile, extern)

U-boot 2021.01 version compilation
随机推荐
如何使用Keil5中的虚拟示波器进行软件仿真
go语言json解析库jsoniter的使用(替换标准库encoding/json)
如何设置树莓派上网功能
Embedded software development stm32f407 buzzer register version
分布式理论
嵌入式软件开发 STM32F407 蜂鸣器 寄存器版
[matlab] matlab lesson 2 - preliminary drawing
The 12th Blue Bridge Cup embedded simulation questions
codeblocks的官网下载与安装
RAC 心跳异常(ipReamsfails)的处理记录和分析
02-FeatureScaling归一化
02 featurescaling normalization
Excel-2
A series of operations of C language string (inverse output of string, mutual conversion of string type with int and double)
Max3232ese problem record and solution
Use MessageBox to realize window confession applet (with source code)
Dhcp-master Automated Deployment
【 pcb】 quelques expériences sur la conception du matériel et le dessin des PCB dans le jeu électrique (mise à jour continue)
记录:VsCode通过ssh连接阿里云
C language macro definition (macro parameter creation string, pretreatment adhesive)