DEV Community

jguo
jguo

Posted on

Learning Golang 102

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()
}
Enter fullscreen mode Exit fullscreen mode

not like this

if i < f()  // wrong!
{           // wrong!
    g()
}
Enter fullscreen mode Exit fullscreen mode

Control structures

  • No do or while loop. Only generalized for, switch, if and select. Both of them accept an optional initialization statement.
  • break and continue 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
}
Enter fullscreen mode Exit fullscreen mode

For

There are three forms.

// Like a C for
for init; condition; post { }

// Like a C while
for condition { }

// Like a C for(;;)
for { }
Enter fullscreen mode Exit fullscreen mode

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

if you only need the second item (value), use the blank identifier

sum := 0
for _, value := range array {
    sum += value
}
Enter fullscreen mode Exit fullscreen mode
  • 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]
}
Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
kevinschweikert profile image
Kevin Schweikert

Im the Switch Syntax the Position of default doesnโ€˜t matter

Collapse
 
jiayanguo profile image
jguo

Thanks.