If
simple
if x > 0 {
return y
}
accept an initialization statement
if err := file.Chmod(0664); err != nil {
log.Print(err)
return err
}
the unnecessary else
is omitted
f, err := os.Open(name)
if err != nil {
return err
}
d, err := f.Stat()
if err != nil {
f.Close()
return err
}
// no else
codeUsing(f, d)
Redeclaration and reassignment
f, err := os.Open(name)
d, err := f.Stat()
err
is declared by the first statement, but only re-assigned in the second.
For
three forms
// Like a C for
for init; condition; post { }
// Like a C while
for condition { }
// Like a C for(;;)
for { }
range
clause
for key, value := range oldMap {
newMap[key] = value
}
// only the first item (key or index)
for key := range oldMap {
handleKey(key)
}
// only the second item (value), use blank identifier (an underscore)
for _, value := range array {
handleValue(value)
}
For strings, the range
breaks out individual Unicode code points by parsing the UTF-8.
for pos, char := range "😀😁" {
fmt.Printf("character %#U starts at byte position %d, cp is %d\n", char, pos, char)
}
// prints out:
// character U+1F600 '😀' starts at byte position 0, cp is 128512
// character U+1F601 '😁' starts at byte position 4, cp is 128513
Go has no comma operator, and ++
, --
are statements not expressions.
parallel assignment (use multiple variables in a for
loop)
// Reverse a
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
Switch
write an if``-``else``-``if``-``else
chain as a switch
func unhex(c byte) byte {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
cases can be presented in comma-separated lists
func shouldEscape(c byte) bool {
switch c {
case ' ', '?', '&', '=', '#', '+', '%':
return true
}
return false
}
no automatic fall through
break / continue / Label:
Type switch
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
}