Go language core beauty 4.3-Multiple return values

Source: Internet
Author: User

In the Go language. function can have multiple return values, this feature we have seen in the previous sample very much, very many standard library functions will return two values, one is expected to get the result of the function execution, and the other is the error value of the function error.

The following program is an improved version number for FindLinks, which can initiate HTTP requests on its own, thus eliminating the need to perform fetch. The HTTP request and the decryption operation may fail. Therefore, FindLinks declares two return values: The list of stored links and the error values. Generally speaking. The parser for HTML constructs the wrong HTML node when it encounters an error, so there is very little failure in parsing the HTML. Once failed. It is most likely caused by an IO error.

Gopl.io/ch5/findlinks2

funcMain () { for_, URL: =RangeOs. args[1:] {links, err: = FindLinks (URL)ifErr! =Nil{FMT. fprintf (OS. Stderr,"FINDLINKS2:%v\n", err)Continue} for_, Link: =RangeLinks {fmt. Println (link)}}}//FindLinks performs an HTTP GET request for URL, parses the//Response as HTML, and extracts and returns the links.funcFindLinks (URLstring) ([]string, error) {resp, err: = http. Get (URL)ifErr! =Nil{return Nil, err}ifResp. StatusCode! = http. Statusok {resp. Body.close ()return NilFmt. Errorf ("Getting%s:%s", URL, resp. Status)} doc, err: = HTML. Parse (resp. Body) resp. Body.close ()ifErr! =Nil{return NilFmt. Errorf ("parsing%s as HTML:%v", URL, err)}returnVisitNil, Doc),Nil}

FindLinks has 4 return statements, and each return returns a pair of values. The first three returns will return the error message encountered during execution, the number one directly returns an error message, followed by two through FMT. Errorf output more specific error messages.

Assuming the findlinks completes successfully, the final return statement returns the list of links to the user for parsing. The error message at this point is nil.

In Finallinks, we must ensure resp. The body is closed and then the network resource is freed, even when the error occurs.

Although the go garbage collection mechanism recycles memory that is no longer in use, it is not assumed that unused operating system resources will be recycled. such as open files, network connections, etc., we should be an explicit recycling!

A multiple return value function returns a set of values to the caller, so the caller must explicitly assign the values to the appropriate variables (assuming they are used later):

links, err := findLinks(url)

Assume that a value is not being used. Be able to assign it to the blank operator (identifier):

// 这里表示忽略返回的错误

a function can return a function that has more than one return value:

func  findlinkslog (url string ) ([]string , error) {log. Printf ( "findlinks%s" , url) 

This feature is very handy when debugging, and we only need a single statement to output all the return values. The following code is equivalent:

log.Println(findLinks(url))links, err := findLinks(url)log.Println(links, err)

The ability to return values of the appliance name to give the return value a sense of understanding, especially if the type of the return value is the same, as follows:

func Size(rect image.Rectangle) (width, height int)func Split(path string) (dir, file string)func HourMinSec(t time.Time) (hour, minute, second int)

Although a good name is very important. But you don't have to take a proper name for each return value.

For example, by convention, the return value of the last bool type of the function indicates whether the function succeeds, and the return value of the error type represents the error message for the function, for these similar conventions. We don't have to think about proper naming.

Assuming that all return values of a function are named, then the return statement of the function omits the operand, which is called a bare return (bare return).

//Countwordsandimages does an HTTP GET request for the HTML//Document URL and returns the number of words and images in it.funcCountwordsandimages (URLstring) (words, imagesint, err Error) {resp, err: = http. Get (URL)ifErr! =Nil{return} doc, err: = HTML. Parse (resp. Body) resp. Body.close ()ifErr! =Nil{err = FMT. Errorf ("parsing HTML:%s", err)return} words, images = Countwordsandimages (doc)return}funcCountwordsandimages (n *html. Node) (words, imagesint) {/* ... */}

This will follow the order of the return values list. Returns all the return values, in the example above, each return statement is equivalent to:

return words, images, err

When a function has multiple return statements and many return values, the bare return can reduce the repetition of the code. But it will make our code difficult to understand. For example, suppose you don't have a detailed review code. It is very difficult to find the first 2 return equivalent to return 0,0,err (the named return value of the function is initialized to the 0 value of the corresponding type by default). The last return is equivalent to return words. Image,nil. Based on the above reasons, it is inappropriate to overuse the bare return.

Practice 5.5:? Implement Countwordsandimages. (Test 4.9 how to participle)

Practice 5.6:? Change the corner function in Gopl.io/ch3/surface (§3.2). Name the return value and use bare return.

Go language core beauty 4.3-Multiple return values

Related Article

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.