Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use functions in golang

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use the function in golang. It is very detailed and has certain reference value. If you are interested, you must finish it.

A function is an organized, reusable block of code used to perform a specified task.

Functions, anonymous functions and closures are supported in the go language, and functions are "first-class citizens" in the go language.

Function definition

The func keyword is used in go language to define functions in the following format:

Func function name (parameter) (return value) {function body}

Among them

The function name consists of letters, numbers, and underscores, but the first letter of the function name cannot be a number, and the function name cannot be repeated in the same package.

Parameters: parameters are composed of parameter variables and types of parameter variables, which are used and separated by multiple parameters.

Return value: the return value consists of the return value variable and its variable type, or you can only write the type of the return value. Multiple return values must be wrapped with () and separated by.

Function body: a block of code that implements a specified function

Let's first define a function that finds the sum of two numbers.

Func sumint (x int, y int) int {return Xeroy}

The parameters and return values of the function are optional, for example, we can implement a function that requires neither arguments nor return values:

The call of func sayHello () {fmt.Println ("Hello Shahe")} function

After defining the function, we call the function by the function name (), for example, we call the function defined above:

Func main () {sayHello () ret: = intSum (10,20) fmt.Println (ret)}

Note that when you call a function that has a return value, you can not receive its return value.

Parameter type abbreviation

Among the parameters of the function, if the type of adjacent variables is the same, you can omit the type, as follows:

Func intSum (x, y int) int {return x + y}

In the above code, the function has two parameters, both of which are of type int, so the type of x can be omitted because y is followed by a type description, and the x parameter is also of that type.

Variable parameter

Variable parameter means that the number of parameters of the function is not fixed, the variable parameter in Go language, by adding after the parameter name. To identify.

Note: a variable parameter is usually used as the last parameter of a function.

For example:

Func intSum2 (x... int) int {fmt.Println (x) / x is a slice sum: = 0 for _, v: = range x {sum = sum + v} return sum} return value

In the go language, the return value of a function is output through the return keyword.

Multiple return value

Functions in the go language support multiple return values, use these variables directly in the function body, and finally return them through the return keyword.

Func calc (x, y int) (sum, sub int) {sum = x + y sub = x-y return} defer statement

Because of the delayed investigation in the go statement, the defer statement can easily deal with resource release problems, such as resource cleanup, file closure, unlocking and recording time.

Timing and case study of defer implementation

In the functions of the GE language, the return statement is not an atomic operation at the bottom, it is divided into two steps: the assignment of the return value and the RET instruction. The timing of defer statement execution is just after the return assignment operation and before the execution of the RET instruction. It is shown in the following figure:

Func F1 () int {x: = 5 defer func () {xx +} () return x} func f2 () (x int) {defer func () {xx +} () return 5} func f3 () (y int) {x: = 5 defer func () {xx +} () return x} func f4 () (x int) { Defer func (x int) {x int +} (x) return 5} func main () {fmt.Println (F1 ()) fmt.Println (f2 ()) fmt.Println (f3 ()) fmt.Println (f4 ())} function advanced variable scope global variable

A global variable is a variable defined outside a function, and it is valid for the entire running cycle of the program. Global variables can be accessed in the function.

Package mainimport ("fmt") var num int = 10func testGlobal () {fmt.Printf ("num =% d\ n", num)} func main () {testGlobal ()} local variable

There are two types of local variables: variables defined within the function can no longer be used outside the function, for example, the variable x defined in the testLocalvar function cannot be used in the following sample code main function:

Package mainimport ("fmt") func testLocalvar () {var x int = 100fmt.Printf ("x% d\ n", x)} func main () {testLocalvar () fmt.Println (x)}

If the local variable and the global variable have the same name, access the local variable first:

Package mainimport ("fmt") var num int = 100func testNum () {num: = 100fmt.Printf ("num=%d\ n", num)} func main () {testNum () / / num= 100}

Next, let's take a look at the variables defined by the statement block, which we usually use on if conditional judgments, for loops, and switch statements.

Package mainimport ("fmt") func testLocalvar (XMagi y int) {fmt.Println (XMagi y) if x > 0 {z: = 100fmt.Println (z)} fmt.Println (z) / / the variable I} func main () {testLocalvar (1Magne2) / / num = 100} function cannot be used as a variable here.

Functions can be passed as variables:

Func main () {F1: = add / / assigns the function add to the variable F1 fmt.Printf ("type of F1 type of% T\ n", F1) / / type of f1:func (int, int) int ret: = F1 (10,20) fmt.Println (ret)} function can be used as an argument

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

}

Anonymous function

Functions can also be used as return values, but in GE language, functions can no longer be defined as before, only anonymous functions can be defined. Anonymous functions are functions without function names. The definition format of anonymous functions is as follows:

Func (parameter) (return value) {function body}

An anonymous function cannot be called like an ordinary function because it does not have a function name. All anonymous functions need to be saved to a variable or executed immediately:

Package mainimport ("fmt") func main () {add: = func (XMagi y int) {fmt.Println (XLECY)} add (10LJ 20) func (XMagi y int) {fmt.Println (XCY)} (10LJ 20)} closure

A closure refers to an entity composed of a function and its associated reference environment. Simply put, closure = function + reference environment. First, let's look at an example:

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} these are all the contents of the article "how to use functions in golang" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report