Go is a new language. Although it borrowings ideas from existing languages, it has unusual features that make effective Go programs different from those written by relatives. Converting C ++ or Java programs directly to Go is unlikely to yield satisfactory results -Java programs are written in Java, not Go. On the other hand, thinking about things from the Go perspective can result in a successful but completely different program. In other words, to write language well, it is important to understand its features and idioms. It is also important to understand the conventions established in Go programming (such as naming, formatting, program construction, etc.) so that you write programs that are easy for other Go programmers to understand.Copy the code
f, err := os.Open(name)
iferr ! =nil {
return err
}
d, err := f.Stat()
iferr ! =nil {
f.Close()
return err
}
codeUsing(f, d)
Copy the code
This example details how the := short statement works. The declaration for calling os.open is:
f, err := os.Open(name)
Copy the code
This statement declares two variables, f and err. A few lines later, the call to f.stat shows:
d, err := f.Stat()
Copy the code
It looks like it declares d and err. Note, however, that err occurs in two statements. This replication is legal: Err is declared in the first statement, but only reassigned in the second. This means that calls to F.stat take the existing ERR variable declared above and give it only a new value.
In the a:= declaration, the variable v may occur even if it has already been declared, if:
- This declaration is in the same scope as the existing declaration of v (if v is already declared in an external scope, this declaration will create a new variable, §),
- The corresponding values in the initialization can be assigned to v and
- The declaration creates at least one other variable.
This unusual feature is purely pragmatic; for example, it is easy to use a single ERR value in a long if-else chain. You’ll see it in use all the time.
§ It’s worth noting here that in Go, function arguments and return values have the same scope as the body of the function, although they are outside the braces that contain the body of the function.
Golang Foreign Language Translation Project golang.org/doc/effecti…