[Translate] effective GO Control structures

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

Control Structures

The control structures of Go is related to those of C and differ in important ways. There is no does or while loop, only a slightly generalized for; switch is more flexible; If and switch accept an optional-initialization statement like that; And there is new control structures including a type switch and a multiway communications multiplexer, select. The syntax is also slightly different:there was no parentheses and the bodies must always be brace-delimited.

Go control structure and C approach but there are some differences in the key. Go does not have a while loop switch with more flexibility if and switch can have an optional initialization statement go adds a new control structure containing type switch commonly used to determine the dynamic type of the interface There are multiple communication multiplexing Select (which will be used in the channel) there are also some small differences in control structures that do not require parentheses but curly braces are necessary.


If

In Go a simple if looks:

The IF statement in go:

If x > 0 {    return y}

Mandatory braces encourage writing simple if statements on multiple lines. It's good style to doing so anyway, especially if the body contains a control statement such as a return or break.

Force the addition of curly braces encourage you to write a simple if statement as well. This is a good code style especially if the statement has a return or break

Since if and switch accept an initialization statement, it's common to see one used to set up a local variable.

If and switch can have initialization statements typically define local variables

If err: = file. Chmod (0664); Err! = Nil {    log. Print (ERR)    return err}

In the Go libraries, you'll find the if an if statement doesn ' t flow into the next statement-that are, the body ends in Break, continue, goto, or return-the unnecessary else is omitted.

In the Go standard library source code can find that else is often omitted, especially if the statement with a break continue Goto or return end

F, err: = OS. Open (name) if err! = Nil {    return err}codeusing (f)

This is an example of a common situation where code must guard against a sequence of error conditions. The code reads well if the successful flow of control runs down the page, eliminating error cases as they arise. Since error cases tend to end in return statements, the resulting code needs no else statements.

The following code shows the error judgments and handling methods that are commonly used in go, so they return directly to the error, so there is no need for the else statement.

F, err: = OS. Open (name) if err! = Nil {    return err}d, err: = F.stat () if err! = Nil {    f.close ()    return err}codeusing (F, D)


Redeclaration Repeating statement

A aside:the last example in the previous sections demonstrates a detail of how the: = Short Declaration Form works. The declaration that calls OS. Open reads,

The example above actually shows how to use: = Declare variable

F, err: = OS. Open (name)//This sentence defines two variables F err
D, Err: = F.stat ()//read data from F

Which looks as if it declares D and err. Notice, though, that's err appears in both statements. This duplication is Legal:err are declared by the first statement, and only re-assigned in the second. This means is the call to F.stat uses the existing ERR variable declared above, and just gives it a new value.

Look at the top two sentences first D and err but have not noticed that err in the above two sentences in the case is legal err just in the first sentence is defined in the second sentence only to give the ERR value that is f.stat used the defined err variable just give it a new value

In a: = declaration A variable v or appear even if it has already been declared, provided:

When the following conditions are met: = declaring an already defined variable V is legal:

    • This declaration are in the same scope as the existing declaration of V (if v are already declared in an outer scope, the DE Claration would create a new variable),
    • The second declaration and V are in the same scope (if V is defined in a function outside the function again V is created a new variable V and overwrites the V outside the function)
    • The corresponding value in the initialization are assignable to V, and
    • The new value is acceptable for V and must be the same type
    • There is at least one and variable in the declaration, is being declared a new.
    • The second declaration must be declared with at least one new variable

This unusual property was pure pragmatism, making it easy-to-use a single ERR value, a-example, in a long if-else chain. You'll see it used often.

This wonderful feature definitely embodies the pragmatism that makes it easier to use err


For

The Go for loop was similar to-but not the same as-c ' s. It unifies for and while and there is no do-while. There is three forms, only one of the which has semicolons.

The For loop in Go is similar to C and it swallowed the while in C to have a struct in go that does not have a for three forms only one uses semicolons

Like a C for and C for loop similar but there are no parentheses here for Init; Condition Post {}//-c whilefor condition {}//like a C for (;;) Dead loop in C for {}

Short declarations make it easy-Declare the index variable right in the loop.

A short form of declaration makes it easy to define a cursor variable at the beginning of the loop

Sum: = 0for I: = 0; I < 10; i++ {    sum + = i}


If you ' re looping a array, slice, string, or map, or reading from a channel, a range clause can manage the loop.

If you want to traverse the array slice string map or read the data from the channel you can use range

For key, Value: = Range Oldmap {    Newmap[key] = value}


If you are need the first item in the range (the key or index), drop the second:

Range returns the key (or cursor position) and the corresponding value such as range an array [' A ', ' B ', ' C '] range results

1 ' a '

2 ' B '

3 ' C ' If you only want the first element of range (above 1 2 3) to write:

For key: = range m {    if expired (key) {        Delete (M, key)    }}

If you have need the second item in the range (the value), use the blank identifier, a underscore, to discard th E First:

If you only want the second element (' a ' B ' C ' above), you can discard the first element returned by the range using a null identifier _:

Sum: = 0for _, Value: = range array {    sum + = value}


For strings, the range does + work for your, breaking out individual Unicode characters by parsing the UTF-8. Erroneous encodings consume one byte and produce the replacement rune U+fffd. The Loop

Go did a lot of work behind the scenes while traversing the string. Use a byte for each Unicode character that cannot be decoded using the UTF8 decoding character and use U+FFFD instead of "U+fffd is" " (U+FFFD)" under this loop

For pos, char: = range "Japanese" {    fmt. Printf ("character%c starts at byte position%d\n", char, POS)}

Will output:

Character day starts at byte position 0character Ben starts at byte position 3character language starts at byte position 6


Finally, Go has no comma operator and + + and--is statements not expressions. Thus If you want to run multiple variables in a for your should use parallel assignment.

Go does not have a comma operator + + and--is a statement rather than an expression if you want to assign values to multiple variables at the same time, you can only:

Reverse afor I, J: = 0, Len (a)-1; I < J; I, j = i+1, j-1 {    a[i], a[j] = A[j], A[i]}


Switch

Go ' s switch is more general than C ' s. The expressions need not being constants or even integers, the cases is evaluated top to bottom until a match is found, and If theswitch have no expression it switches on true. It ' s therefore possible-and idiomatic-to write an if-else-if-else chain as a switch.

The switch structure of GO is more general than c its expression does not need to be constant or integer case statements are executed from scratch until they match a case, so you can use switch to overwrite If-else-if-else

Func Unhex (c byte) byte {    switch {case    ' 0 ' <= C && c <= ' 9 ':        return C-' 0 ' case    ' a ' <= C && C <= ' F ':        return C-' a ' + Ten case    ' a ' <= C && c <= ' F ':        return C-' a ' + 10
  
   }    return 0}
  


There is no automatic fall through, but cases can be presented in comma-separated lists.

The go switch is not like C, and if no break will cause a case to be matched after it has been executed, it can be done with a comma-separated list.

Func shouldescape (c byte) bool {    switch c {case    ', '? ', ' & ', ' = ', ' # ', ' + ', '% ':        return True    }
  return false}


Here's a comparison routine for byte slices that uses the switch statements:

The following function uses two switch to compare two byte slice

Compare returns an integer comparing the both byte slices,//lexicographically.//The result would be 0 if a = = B, 1 if A < B, and +1 if a > Bfunc Compare (A, b []byte) int {for    I: = 0; i < Len (a) && i < Len (b); i++ { C1/>switch {case        a[i] > B[i]:            return 1 case        A[i] < B[i]:            return-1        }    }    switch {    Case Len (a) < Len (b):        return-1 case    len (a) > len (b):        return 1    }    return 0}


A switch can also is used to discover the dynamic type of A interface variable. Such a type switch uses the syntax of a type assertion with the keyword type inside the parentheses. If The switch declares a variable in the expression, the variable would have the same corresponding type in each clause.

A switch can be used to determine the dynamic type of an interface, type switch, which uses types assertion T. (type) t is an interface variable this usage is only valid in switch

Switch T: = Interfacevalue. (type) {default:    FMT. Printf ("Unexpected type%T", T)  //%T Prints typecase bool:    FMT. Printf ("Boolean%t\n", t) Case int:    FMT. Printf ("integer%d\n", t) case *bool:    fmt. Printf ("Pointer to Boolean%t\n", *t) Case *int:    fmt. Printf ("Pointer to Integer%d\n", *t)}

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.