Golang Grammar Learning (ii): Control statements, functions, and error handling.

Source: Internet
Author: User
Tags case statement loop case uppercase letter
This is a creation in Article, where the information may have evolved or changed.


In the grammar (i), we learn the basic elements of the basic data types, variables, constants, and so on in go, and in this section we will learn how to organize these elements and eventually write code that can be executed.

In this section include:

The Process Control statement in go;

The use of functions in go;

Go special error handling method;

Process Control statements in the Golang

In the specific programming, it is necessary to use some special statements to implement certain functions, such as using loop statements to iterate, using the Choice Statement Control program execution mode. These statements are in any one of the programming languages

will be supported in Golang, in addition to support common loops, conditional selection statements, but also support jump statements, the following are the ways to see how these statements are used.

Conditional statement If, else if, else,...

Usage:

If expression {      //note curly brackets must be on the same line as if, including the following else and {also; the expression does not need parentheses around the body                  //And no matter how many lines in the program require curly braces, this is a difference from C ...} else{Program Body ...}
Note that you can have an assignment for an expression after if, separated by semicolons.

SELECT statement Switch

In fact, it is similar to the function of the IF statement, except that the choice statement is more flexible and can reduce the branch overhead of if else, similar to the use of switch in C language,

The switch  expression {//and the IF statement, the expression does not need to use parentheses, while switch and {on the same line case condition one: Program body case Condition Two: Program body case ... default: Program Body}

A big difference between this and the C language is that you don't need to use break to force the end in the body of each case condition. If you need to execute the following case statement, you can do so by adding the Fallthrough keyword.

Loop statement for

Go also supports looping statements, but unlike other languages such as C, go supports only for loops and does not support using while.

Use mode one: the most basic usage for variable initialization; Cycle end condition; Variable change expression {program body ...} Use mode two: Infinite loop case, similar to C in the for (;;) For {program body ...}

Also allows the use of balanced multiple assignments in the for expression, such as the following to reverse an array in go:

A: = [] int {1,2,3,4,5,6}fori, J: = 0, Len (a)-1; i<j; I, j = i + 1, j-1 {a[i], a[j] = A[j], A[i]}

Note You can also use the break statement in the go language.

Jump Statement Goto

As a beginner, I do not know why go language will support goto this usage, in the early days about the shortcomings of Goto, has been dijkstra and other people sent the article focused discussion, here do not do specific introduction, and so on after-depth study to add, why designers to design.

The above is Golang supported four kinds of program control statements, in order to complete the code, we also need to encapsulate some specific functions, the following we introduce the use of functions in Golang.

The use of functions in Golang

Definition of a function

Unlike other languages, such as the C language, the functions in Golang are defined as follows: Func keyword function name (parameter 1, parameter 2, ...) (return value 1, return value 2, ...)  {function Body ...} For example, the following implementation adds two variables to the function: Func  Add (a int, b int) (ret int, err error) {return a+b, nil}

If the return value is only one then the parentheses can be saved, and if more than one argument is of the same type, then the type of the preceding variable is omitted.

Call to function

The function is called by importing the package and then using the function in the same way as the package.

It is important to note that the case of the function name is Golang in the box, and only the function with the beginning of the uppercase letter can be used by the other package. and use smaller letters.

Functions that begin with can only be visible within this package. The naming conventions for variable names are similar.

Support for indeterminate parameters

In Golang, the function also supports indefinite arguments, that is, the function can accept any number of arguments of any type.

For example, the following function MyFunc can accept variables of any number of type int as arguments:

Func myfunc (args ... int) {for_,arg: = range args {fmt. Println (ARG)}}

At call time:

MyFunc (2,3,4)

Mufunc (1,3,7,13)

If you support any type of argument, you only need to change int to interface{}  to be able to func  myprintf (args ... interface{}) {Program body ...}

Multiple return values

I have already introduced the Golang function is to support multiple return values, if the return value is not required then directly can be set to the default of the corresponding value can be.


Anonymous functions and closures

If C or C + + programmers may be unfamiliar with the concept of anonymous functions. Because the concept of anonymous functions is not supported in these languages, the function name is a pointer used to invoke a function.

There are very anonymous functions in Go and javascript,c# and objective-c.

From the formal point of the function, the anonymous function means that the function name is not required when defining a function. In terms of usage, I personally think that the anonymous function is intended to be more flexible with functions, because in c,c++

We cannot define another function in one function. And sometimes we need to use it, so the anonymous function can do that by defining an anonymous function in a function that does not define the function name.

, and this anonymous function can call some variables of this function's peripheral function. In fact, this is the function of closures. Let's take a look at the definition of an anonymous function and then introduce the concept of closure.

Defines an anonymous function that implements the addition of two numbers

Func (A, b int) int {

Return a+b

}

We can assign this anonymous function to a variable and then invoke the anonymous function through this variable:

F: = Func (A, b int) int {

Return a + b

}

We can then use F (x, Y) to invoke the Func

Closed Package

About closures If there is no concept before, such as me, you can first look at this link: http://ahomeeye.iteye.com/blog/1050178

Here is my personal opinion, in fact, in simple terms,

A closure is a block of code, and this block of code may be an anonymous function, similar to what is defined above, the special place of this code block is that he can use the variables that he defines in the same level environment. Of course this

It's just a little bit of my personal understanding. Here is an example of the Seven Bull team book:

Package Mainimport ("FMT") func main () {var J int = 5a:= func () (func ()) {                                  //defines a closure here. By a point to this closure var i int = 10return func () {fmt. Printf ("I, J:  %d,%d \ n", I, j)//closures can use variable J}} () J *= 2a ()}//execution results are: I, J:10, 5i, J:10, 10

More on the closure of the knowledge we still use the back of the time to talk about it, as long as we understand this concept can be.

Let's look at the Golang in the

Error handling

The key to writing robust programs is the handling of errors, and the possibility of exception-catching. Good support for error handling in Golang, including

Error interface

With the error interface provided by Golang, users can define the type of error themselves, where the error () method of the error interface needs to be implemented. These specific implementation details are learned below

Golang the object-oriented time to do the introduction.

Defer keywords

Defer the meaning of postponing the extension. In Golang, adding defer to a statement guarantees that the modified statement part can be executed either when the program exits normally or when it terminates abnormally.

It is generally necessary to close the file descriptor at the time of Io.

Like what:

Defer File.close ()

Note that the statements in defer are organized in the form of a stack, and the last declaration is called first.

Finally say panic () and recover ()

This is the Golang built-in two functions used to report and handle run-time errors and errors in the program.

When the Panic () function is called, the normal function execution process will abort immediately, but statements that use the DEFER keyword delay execution will expand normally.

The Recover function is similar to catching exceptions in high-level programming languages, and using the Recover () function in Golang can stop and terminate the error-handling process.

Summarize

The above is the grammar (2) in the content of learning, mainly to learn the Golang in the process of control statements, the use of functions in Golang, and the processing of errors. Some of these characteristics are not very deep experience, the latter will deepen learning.

by Lingtao Kong in Nanjing 2015/06/16 reprint please specify the Source: http://blog.csdn.net/michael_kong_nju/article/details/46507821

Related Article

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.