This is a creation in Article, where the information may have evolved or changed.
The syntax and use of Golang are very simple and clear, there is no fancy syntax sugar, and no redundant keywords.
But even in such a concise language, there are still some things that are less straightforward and require attention, such as the following 2 points.
Interface is assigned nil Pointer and becomes non-nil
package main ( "bytes" "FMT" "IO" ) func main () {var b *bytes. Buffer if b = = nil {fmt. Println ( "B is nil" )} f (b)}func f (out IO. Writer) {if out = = nil {fmt. Println ( "nil" )} else {fmt. Println ( "No-nil" ) //out. Write ([]byte ("xxxx"))//There'll cause panic }}
interface consists of 2 parts, type and value , when calling Func F, the type of Out is set to *bytes. Buffer, value is set to nil.
At this time out! = nil, as though out value == nil , buttype !=nil
It is easy to panic the runtime when writing code without paying attention to it.
There are 2 kinds of return values for type judgments
The Golang can be transformed by type judgments.
Type judgment, the transformed code can return a value, or it can return 2 values (additional judgment result OK).
package mainimport ( "fmt" "io" "os")func main() { var w io.Writer w = os.Stdout rw, ok := w.(*os.File) // 可以正常执行 // rw := w.(*os.File) // 也可以正常执行 fmt.Println(rw, ok)}
The return value of the same piece of code, but there are 2 cases, channel and map also has the above phenomenon: (if the following code is correct)
varmap["key"]varmap["key"]var val = <- chvar val, ok = <- ch
The implementation of this syntax is simple, that is, Golang in the type of judgment, according to the syntax tree check = whether there is a comma (that is, comma), if there is a return of 2 values, not return a value.
For details, refer to: http://stackoverflow.com/questions/30129206/golang-return-multiple-values-issue/30135334
Blog Source: http://blog.iotalabs.io/golang-zhi-de-zhu-yi-de-di-fang-2ze/