- reference: TDD, Effective Go. Go Chinese Docs
Control structures
In Go language, there is only if , for , switch as control structure while no do, while loop.
- Same with other language:
break,continuestatements is the same as others - Different :
- in
switchstructure,typeis optional label select
- in
Syntax in Go: No need parentheses while the body must always be brace-delimited.
if
Ordinary syntan: Writting simple
ifin multiple lines.1
2
3if x > 0 {
return y
}Intersting syntax:
ifwith initialization statement1
2
3
4if err := file.Chmod(0664); err != nil {
log.Print(err)
return err
}
for
There are three forms in for syntaxs:
1 | // Like a C for |
for with range:
range statements is a good way to loop array, slice, map, channel, the syntax is :
1 | for key, value := range oldMap { |
If you only need the first item in the range (the key or index), drop the second:
1 | for key := range m { |
If you only need the second item in the range (the value), use the blank identifier, an underscore, to discard the first:
1 | sum := 0 |
- Range does more work for
string:Breaking out individual Unicode code points by parsing the UTF-8. Erroneous encodings consume one byte and produce the replacement rune U+FFFD.
1 | for pos, char := range "日本\x80語" { // \x80 is an illegal UTF-8 encoding |
switch
switch has the same mwaning as other language. In go language, if the switch has no expression it switches on true. It’s therefore possible—and idiomatic—to write an if-else-if-else chain as a switch.
1 | func unhex(c byte) byte { |
There is no automatic fall through, but cases can be presented in comma-separated lists.
1 | func shouldEscape(c byte) bool { |
Type switch
A switch can also be used to discover the dynamic type of an 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 will have the corresponding type in each clause. It’s also idiomatic to reuse the name in such cases, in effect declaring a new variable with the same name but a different type in each case.
1 | var t interface{} |