What is the method of calling functions in Go language?

青灯夜游
Release: 2022-12-01 19:32:00
Original
6733 people have browsed it

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.

What is the method of calling functions in Go language?

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 函数名(形式参数列表)(返回值列表){
    函数体
}
Copy after login

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:

返回值变量列表 := 函数名(参数列表)
Copy after login

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)
Copy after login

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()
Copy after login
Copy after login

在这段代码中,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)
}
Copy after login
Copy after login

代码输出结果:

1 2
Copy after login

纯类型的返回值对于代码可读性不是很友好,特别是在同类型的返回值出现时,无法区分每个返回参数的意义。

2) 带有变量名的返回值

Go语言支持对返回值进行命名,这样返回值就和参数一样拥有参数变量名和类型。

命名的返回值变量的默认值为类型的默认值,即数值为 0,字符串为空字符串,布尔为 false、指针为 nil 等。

下面代码中的函数拥有两个整型返回值,函数声明时将返回值命名为 a 和 b,因此可以在函数体中直接对函数返回值进行赋值,在命名的返回值方式的函数体中,在函数结束前需要显式地使用 return 语句进行返回,代码如下:

func namedRetValues() (a, b int) {
    a = 1
    b = 2
    return
}
Copy after login
Copy after login

代码说明如下:

  • 第 1 行,对两个整型返回值进行命名,分别为 a 和 b。
  • 第 3 行和第 4 行,命名返回值的变量与这个函数的布局变量的效果一致,可以对返回值进行赋值和值获取。
  • 第 6 行,当函数使用命名返回值时,可以在 return 中不填写返回值列表,如果填写也是可行的,下面代码的执行效果和上面代码的效果一样。
    func namedRetValues() (a, b int) {
        a = 1
        return a, 2
    }
    Copy after login
    Copy after login

提示

同一种类型返回值和命名返回值两种形式只能二选一,混用时将会发生编译错误,例如下面的代码:

func namedRetValues() (a, b int, int)
Copy after login
Copy after login

编译报错提示:

mixed named and unnamed function parameters
Copy after login

意思是:在函数参数中混合使用了命名和非命名参数。

【相关推荐: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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!