golang basic data types

golang control structure (1)

 

This is no smell Gangster learning tutorial written golang

   

   1.if-else structure

if condition1 {
    // do something    
} else if condition2 {
    // do something else    
}else {
    // catch-all or default
}
Basic and java the same, but without the condition in parentheses, but left parenthesis must follow the conditions, not a single line, java there is no limit.

2. Multi return value
which is characteristic of golang, java multi return value, we generally use, or some set of objects returned, such as a pair of special like.
Go function of language is often used to perform two return values to represent success: a value and return true if successful; return zero (or nil) and false indicates failure.
A type of error may also be used in place of the second variable return value: if executed successfully, error value is nil, or it will contain the corresponding error message (error Go language type error:  var err error).
Thus, it is an obvious need to test the results of an if statement; due to its sign, this form also known as comma, ok mode (pattern).
f, err := os.Open(name)
if err != nil {
    return err
}
doSomething(f) // 当没有错误发生时,文件对象被传入到某个函数中
doSomething

3 switch
more flexible structure using the switch on the Go language. It accepts any form of expression:
switch var1 {
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}

It may be any type of var1, while val1 val2 and may be any value of the same type. Or type is not limited to a constant integer, but must be the same type; or end result is the same type of expression. Before braces  { must switch the keywords on the same line.

A plurality of possible values can be simultaneously tested meet the criteria, they are separated by commas, such as: case val1, val2, val3.

Each  case branch is unique, individually tested from top to bottom, until the match. (Go fast search algorithm to use language test match conditions and circumstances switch case branches, until the matching algorithm to a case or enter default condition so far.)

Once you have successfully matched to a branch, in the corresponding code will complete execution exit entire switch code block, which means you do not need to use special  break statement to indicate the end.

If, after completion of each branch code execution, but also want to continue the implementation of the follow-up branch of code, you can use  fallthrough keywords to achieve their goals.
switch i {
    case 0: fallthrough
    case 1:
        f() // 当 i == 0 时函数也会被调用
}


Guess you like

Origin www.cnblogs.com/dream-again/p/11489021.html