In the Go language, after defining a function, we can call the function through "function name ()", the syntax is "return value variable list = function name (parameter list)". When "()" contains multiple parameters, the parameter variables are separated by commas and do not need to end with a semicolon; in the "return value variable list", multiple return values are separated by commas.
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
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 Go language is a compiled language, the order in which functions are written is irrelevant. In view of readability requirements, it is best to write the main() function at the front of the file, and other functions in a certain logical order. Writing (e.g. 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).
When the function executes to the last line of the code block }
It will exit before the return statement. The return statement can have zero or more parameters, and these parameters will be used as the return value. Used by the caller, a simple return statement can also be used to end the infinite loop of for, or to end a goroutine.
There are three types of functions in the Go language:
- Ordinary functions with names
- Anonymous functions or lambda functions
- Methods
Ordinary function declaration (definition)
Function declaration includes function name, formal parameter list, return value list (can be omitted) and function body.
func 函数名(形式参数列表)(返回值列表){ 函数体 }
The formal parameter list describes the parameter name and parameter type of the function. These parameters are used as local variables, and their values are provided by the parameter caller. The return value list describes the variable name and type of the function return value. If the function Returns an unnamed variable or no return value. The parentheses in the return value list can be omitted.
Call function
After the function is defined, the current code can be jumped to the called function for execution by calling. The function local before calling The variables will be saved and will not be lost. After the called function finishes running, it will resume to the next line of the calling function and continue to execute the code. The previous local variables can also continue to be accessed.
Local variables within a function can only be used in the function body. After the function call is completed, these local variables will be released and invalid.
The function calling format of Go language is as follows:
返回值变量列表 := 函数名(参数列表)
The following is a description of each part:
- Function name: the name of the function that needs to be called.
- Parameter list: Parameter variables are separated by commas and do not need to end with a semicolon.
- Return value variable list: Multiple return values are separated by commas.
For example, the addition function calling style is as follows:
result := add(1,1)
The return value of the function
Go language supports multiple return values, multiple return values It is easy to obtain multiple return parameters after function execution. Go language often uses the last return parameter in multiple return values to return errors that may occur during function execution. The sample code is as follows:
conn, err := connectToNetwork()
conn, err := connectToNetwork()
在这段代码中,connectToNetwork 返回两个参数,conn 表示连接对象,err 返回错误信息。
其它编程语言中函数的返回值
- C/C++ 语言中只支持一个返回值,在需要返回多个数值时,则需要使用结构体返回结果,或者在参数中使用指针变量,然后在函数内部修改外部传入的变量值,实现返回计算结果,C++ 语言中为了安全性,建议在参数返回数据时使用“引用”替代指针。
- C# 语言也没有多返回值特性,C# 语言后期加入的 ref 和 out 关键字能够通过函数的调用参数获得函数体中修改的数据。
- lua 语言没有指针,但支持多返回值,在大块数据使用时方便很多。
Go语言既支持安全指针,也支持多返回值,因此在使用函数进行逻辑编写时更为方便。
1) 同一种类型返回值
如果返回值是同一种类型,则用括号将多个返回值类型括起来,用逗号分隔每个返回值的类型。
使用 return 语句返回时,值列表的顺序需要与函数声明的返回值类型一致,示例代码如下:
func typedTwoValues() (int, int) { return 1, 2 } func main() { a, b := typedTwoValues() fmt.Println(a, b) }
func typedTwoValues() (int, int) { return 1, 2 } func main() { a, b := typedTwoValues() fmt.Println(a, b) }
代码输出结果:
1 2
纯类型的返回值对于代码可读性不是很友好,特别是在同类型的返回值出现时,无法区分每个返回参数的意义。
2) 带有变量名的返回值
Go语言支持对返回值进行命名,这样返回值就和参数一样拥有参数变量名和类型。
命名的返回值变量的默认值为类型的默认值,即数值为 0,字符串为空字符串,布尔为 false、指针为 nil 等。
下面代码中的函数拥有两个整型返回值,函数声明时将返回值命名为 a 和 b,因此可以在函数体中直接对函数返回值进行赋值,在命名的返回值方式的函数体中,在函数结束前需要显式地使用 return 语句进行返回,代码如下:
func namedRetValues() (a, b int) { a = 1 b = 2 return }
func namedRetValues() (a, b int) { a = 1 b = 2 return }
代码说明如下:
- 第 1 行,对两个整型返回值进行命名,分别为 a 和 b。
- 第 3 行和第 4 行,命名返回值的变量与这个函数的布局变量的效果一致,可以对返回值进行赋值和值获取。
- 第 6 行,当函数使用命名返回值时,可以在 return 中不填写返回值列表,如果填写也是可行的,下面代码的执行效果和上面代码的效果一样。
func namedRetValues() (a, b int) { a = 1 return a, 2 }
func namedRetValues() (a, b int) { a = 1 return a, 2 }
提示
同一种类型返回值和命名返回值两种形式只能二选一,混用时将会发生编译错误,例如下面的代码:
func namedRetValues() (a, b int, int)
func namedRetValues() (a, b int, int)
编译报错提示:
mixed named and unnamed function parameters
意思是:在函数参数中混合使用了命名和非命名参数。
【相关推荐:Go视频教程】
The above is the detailed content of What is the method of calling functions in Go language?. 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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

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

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment