Semicolons
Like C, Go's formal grammar uses semicolons to terminate statements, but unlike in C, those semicolons do not appear in the source.
One consequence of the semicolon insertion rules is that you cannot put the opening brace of a control structure (if, for, switch, or select) on the next line.
if i < f() {
g()
}
not like this
if i < f() // wrong!
{ // wrong!
g()
}
Control structures
- No
do
orwhile
loop. Only generalizedfor
,switch
,if
andselect
. Both of them accept an optional initialization statement. -
break
andcontinue
statements take an optional label to identify what to break or continue;
If with an initialization statement.
if err := file.Chmod(0664); err != nil {
log.Print(err)
return err
}
For
There are three forms.
// Like a C for
for init; condition; post { }
// Like a C while
for condition { }
// Like a C for(;;)
for { }
range
clause can manage the loop. For key and value data, like map, if you only need the first item (key), drop the second.
for key := range m {
if key.expired() {
delete(m, key)
}
}
if you only need the second item (value), use the blank identifier
sum := 0
for _, value := range array {
sum += value
}
- Go has no comma operator and ++ and -- are statements not expressions.
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
switch
The expressions need not be constants or even integers, the cases are evaluated top to bottom until a match is found (default order doesn't matter seems. Need to check).
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
Top comments (2)
Im the Switch Syntax the Position of
default
doesnโt matterThanks.