Go语言圣经-函数多返回值 1.在Go中,一个函数可以返回多个值 2.许多标准库中的函数返回2个值,一个是期望得到的返回值,另一个是函数出错时的错误信息 3.如果一个函数将所有的返回值都显示的变量名,那么该函数的return语句可以省略操作数。这称之为bare return。
练习 5.5: 实现countWordsAndImages。(参考练习4.9如何分词)
package main
import (
"fmt"
"golang.org/x/net/html"
"net/http"
"os"
"strings"
)
/*
练习 5.5: 实现countWordsAndImages。(参考练习4.9如何分词)
*/
func main() {
words, images, _ := CountWordsAndImages(os.Args[1])
fmt.Printf("文字:%d,图片:%d \n",words,images)
}
// CountWordsAndImages does an HTTP GET request for the HTML
// document url and returns the number of words and images in it.
func CountWordsAndImages(url string) (words, images int, err error) {
resp, err := http.Get(url)
if err != nil {
return
}
doc, err := html.Parse(resp.Body)
resp.Body.Close()
if err != nil {
err = fmt.Errorf("parsing HTML: %s", err)
return
}
words, images = countWordsAndImages(doc)
//bare return
return
}
func countWordsAndImages(n *html.Node) (words, images int) {
texts, images := visit3(nil,0, n)
for _, v := range texts {
v = strings.Trim(strings.TrimSpace(v), "\r\n")
if v == "" {
continue
}
words += strings.Count(v, "")
}
//bare return
return
}
//递归循环html
func visit3(texts []string, imgs int, n *html.Node) ([]string, int) {
//文本
if n.Type == html.TextNode {
texts = append(texts, n.Data)
}
//图片
if n.Type == html.ElementNode && (n.Data == "img") {
imgs++
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Data == "script" || c.Data == "style" {
continue
}
texts,imgs = visit3(texts, imgs, c)
}
//多返回值
return texts, imgs
}
练习 5.6: 修改gopl.io/ch3/surface (§3.2) 中的corner函数,将返回值命名,并使用bare return。 这个很简单就不贴了