Notable places to Golang (2)

Source: Internet
Author: User
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/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.