Old Shong Golang notes-control statements

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

The control statements in go are more streamlined, with only if, for, select, and switch. But they are more flexible when used

If

In the conditional statement *if* in Go, the statement block is executed if the conditional part evaluates to **true**, otherwise the Else statement block (if there is an else) is the same logic as in other languages, but there are some differences in go.

    • An IF condition expression cannot use curly braces * * () * * contain
    • The If statement code snippet must use **{}**, and the opening parenthesis must be on the same line as if
    • An if conditional expression can precede an initialization statement, supports parallel assignments, but does not support multiple assignment statements

Assignment + conditional judgment

if a, b := 21, 3; a > b {    fmt.Println("a>b ? true")}

A variable declared before an if condition expression can only be used in a IF-ELSE statement block.

if a, b := 21, 31; a > b {    fmt.Println("a>b ? true")}else {    fmt.Println(a,b) //Ok}fmt.Println(a,b)    //error: undefined a ,undefined b

It is also important to note that if you include return in If-else, the compiler cannot resolve the retrun in else, causing the method to be missing a return, which is currently supported by version 1.1.

func getName(id int) string {    if id == 1 {        return "YourName"    }else {        return "MyName"      }    

This code compiles without passing, error message: function ends without a return statement, this is intentional when designing go, it can also be said to be a bug (see: https://code.google.com/p/go/ ISSUES/DETAIL?ID=65), this is a coding style, that is, in the IF statement block to do return processing, and else do not process, but continue to execute the code behind If-else, so as to reduce a code indentation, You do not need to remember the handling of the Else statement block when you understand the code. Of course, if you want to write this, you can also do special processing, add the statement **panic ("") in the last line of the function * *

It is useful to include initialization statements in If. For example, in the case of file processing, the dictionary entry needs to be judged whether the operation is successful, and only if it succeeds, it can be processed by If-else.

if err := file.Chmod(0664); err != nil {    log.Print(err)    return err}if v,err :=myMap[key];err != nil {    log.Print(err)    return err}else {    //do something with v}

For

Other control statements that loop through in Go are the only for. For the same is also more flexible, for there are three kinds of forms.

    • General usage for Init; Condition;post {}
    • While for condition {}
    • Dead loop for {}

Because go does not have a comma expression, and + + and--is a statement rather than an expression, if you want to execute multiple variables in for, you need to use a parallel assignment

for i, j := 1, 10; i < j; i,j=i+1,j+1 {  //死循环    fmt.Println(i)}

and cannot be written

for i, j := 1, 10; i < j; i++,j++ {    fmt.Println(i)}

The for condition is executed once per loop body, so it is important to be careful not to make the calculations in condition simple, but not complex, in the actual development process.

for i,j :=0,len(str); i<j ; i++ {    fmt.Println(str[i])}

And don't write it (it's just a demo)

for i=0; i< len(str); i++ {    fmt.Println(str[i])}

In addition, for is the way to traverse String,array,slice,map,chanel, while the use of reserved word rang can be handled flexibly. Rang is an iterator that can return different things based on different content.

    • For Index,char: = range String {}
    • For Index,value: = range Array {}
    • For index,value: = Range Slice {}
    • For key,value: = range Map {}

It is important to note that the byte index position and the UTF-8 format Rune type Data (Int32) are obtained when For+rang traverses the string.

for pos, value := range "Go在中国" {    fmt.Printf("character '%c' type is %T value is %v, and start at byte position %d \n", value,value,value, pos)    str :=string(value)  //convert rune to string    

Break and Continue

In addition, break and continue,break are used in the loop to exit the loop, and continue is used to terminate the execution of the loop body and proceed to the next loop.

sum := 0for {    if sum > 10 {        break    }    sum += 2}fmt.Println(sum) // sum=12

Break can also exit the specified loop body

    sum := 0myforLable:    for {        for i := 0; i < 10; i++ {            if sum > 200 {                break myforLable //将退出循环体for{}            }            sum += i        }    }    fmt.Println(sum)

Switch

Switch is the most flexible type of control statement, which can be either a constant or a string, or an expression without an expression, as if it were if-else-else.

General usage: As with other language switch basically, different does not need to add break in each case, but instead hides break, of course you can show join break

switch ch {    case '0':        cl = "Int"    case '1':        cl = "Int"    case 'A':        cl = "ABC"        break //可以添加    case 'a':        cl = "ABC"    default:        cl = "Other Char" }

This code can be written (fallthrough means to continue executing the following case instead of exiting switch)

switch ch {case '0':     fallthrough   //必须是最后一个语句case '1':    cl = "Int"case 'A': case 'a':    fallthrough    cl = "ABC"    //errordefault:    cl = "Other Char"}

If multiple matching results correspond to the same code snippet, you can list all occurrences in one case

switch ch {    case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':        cl = "Int"    case 'A', 'B', 'C', 'D',  'a', 'b', 'c', 'd', 'e':        cl = "ABC"    default:        cl = "Other Char"}

The same switch can have no expression, use a Boolean expression in the case, such as If-else-

switch {    case '0' <= ch && ch <= '9':        cl = "Int"    case ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'):        cl = "ABC"    default:        cl = "Other Char"}

Here is an example of switch writing (no practical meaning):

func Compare(a, b interface{}) (int, error) {    aT := reflect.TypeOf(a)    bT := reflect.TypeOf(b)    if aT != bT {        return -2, errors.New("进行比较的数据类型不一致")    }    switch av := a.(type) {    default:        return -2, errors.New("该类型数据比较没有实现")    case string:        switch bv := b.(type) {        case string:            return ByteCompare(av, bv), nil        }    case int:        switch bv := b.(type) {        case int:            return NumCompare(av, bv), nil        }    }    return -2, nil}

Select

There's another control statement, select, to learn when we talk about Chan.

Previous (arrays and slices)

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.