36. Notes Go language-functions

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

36. Notes Go language-functions

function is the basic part of building a go program. Go does not allow functions to be nested. However, you can use anonymous functions to implement it.

Scope

In go, variables defined outside the function are global, and variables defined inside the function are local to the function. If the name overrides-a local variable has the same name as a global variable-the local variable overrides the global variable when the function executes.

Code:

Package Main

var a = 6

Func Main () {

P ()

Q ()

P ()

}

Func p () {

println (a)

}

Func Q () {

a:= 5

println (a)

}

Output:

6

5

6

Multi-value return

Go a very special feature (for compiled languages) is that functions and methods can return multiple values (Python and Perl can also). This can be used to improve a lot of bad practice usage in C programs: the way to modify parameters, return an error (for example, if you encounter EOF, return-1). In go, write returns a count value and an error: "Yes, you write some bytes, but because of the device exception, not all are written." ”

Code:

Package Main

Func Main () {

a:= []byte{' 1 ', ' 2 ', ' 3 ', ' 4 '}

Varx int

println (Len (a))

Fori: = 0; I < Len (a); {

                                                                                    x,i = Nextint (A, i)

println (x)

}

}

Func Nextint (b []byte, I int) (int, int) {

x:= 0

                                        // Assuming all the numbers are

For I < Len (b); i++ {

x= x*10 + int (b[i])-' 0 '

}

RETURNX, I

}

Without tuples as native types, multiple return values may be the best choice. You can accurately return the desired value without overloading the domain space to a specific error signal.

Named return value

The return value or result parameter of the GO function can specify a name and be used as the original variable, just like the input parameter. If they are named, they are initialized with 0 values of their type at the beginning of the function, and if the function executes a return statement without arguments, the current value of the resulting parameter is returned as the return value. With this feature, it is allowed (again) to do more with less code.

Names are not mandatory, but they can make the code more robust and clear: this is the document. For example, the Nextpos return value of the named int type can indicate which one represents which.

Because named results are initialized and associated with a non-decorated return, they can be very simple and clear.

Delay Code

Suppose you have a function that opens the file and reads it a few. In such a function, there is often a place to return early. If you do this, you need to close the working file descriptor.

To solve this, go has a defer statement. The function specified after defer is called before the function exits.

Deferred functions are executed in the order of last in, first out (LIFO).

A function symbol is something called a closure.

Variable parameter

The function that accepts the argument is a variable number of arguments. To do this, you first need to define the function to accept the argument.

Arg ... int tells go that the function accepts an indefinite number of arguments. Note that the types of these parameters are all int.

function as a value

Just like everything else in go, the function is also a value.

For example, code:

Package Main

Func Main () {

a:= func () {

println ("Hello")

}

A ()

}

Callback

When a function is a value, it can be easily passed to other functions, and then it can be used as a callback.

Panic (Panic) and recovery (Recover)

Go has no exception mechanism like Java: You cannot throw an exception. As an alternative, it uses the panic and recovery (panic-and-recover) mechanism. Be sure to remember that this should be used as a last resort and that your code should have no or little scary things. This is a powerful tool to use it wisely.

Panic

Panic is a built-in function that interrupts the original control flow and enters a frightening process. When function f calls panic, the execution of the function f is interrupted, and the delay function in F executes normally, and then F returns to the place where it was called. Where the call is made, the behavior of F is like calling panic. This process continues up until all goroutine are returned when the program crashes. Panic can be directly called panic generation. It can also be generated by a run-time error, such as an array that accesses out of bounds.

Recover

A built-in function that allows Goroutine to recover from a panic-entering process. The recover is only valid in the delay function.

Corresponding to the exception mechanism, this error mechanism of Go may be called Panic mechanism: when you encounter it should feel panic (panic), and then should be restored (recover) it. During normal execution, the call recover returns nil and has no other effect. If the current goroutine is in panic, call recover can capture the input value of panic and return to normal execution.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.