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。
这个很简单就不贴了

最新文章

  1. java类的初始化块/执行顺序,实例化对象数据赋值
  2. NYOJ题目596谁是最好的Coder
  3. 形形色色的下拉菜单 (css3)
  4. string(Integer)类的equals和==区别和联系(验证密码的时候用得到)
  5. 【C#学习笔记】List容器使用
  6. Java Socket(2): 异常处理
  7. 利用over开窗函数取第一条记录
  8. 返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API
  9. 8个不可不知的Mac OS X专用命令行工具【转】
  10. MetaProducts Offline Explorer使用简易教程
  11. 解决 Excel 打开 UTF-8 编码 CSV 文件乱码的 BUG
  12. struts2-Action处理请求参数
  13. jquery中的ajax方法参数
  14. [转]SVN使用log,list,cat,diff查看所有及特定文件版本信息
  15. 第二章 初识JSP
  16. 【网络流】【BZOJ1070】【SCOI2007】修车
  17. linux 常见技巧
  18. 【.NET Core项目实战-统一认证平台】第五章 网关篇-自定义缓存Redis
  19. UVA 11426 (欧拉函数&&递推)
  20. gentoo rt-thread pkgs --update except Exception, e:

热门文章

  1. 【BZOJ2589】 Spoj 10707 Count on a tree II
  2. Ubuntu系统常见问题解决
  3. 关于GROUP BY和聚合函数
  4. 网络基础、多线程、ftp任务铺垫
  5. Swift5 语言指南(二十二) 扩展
  6. django 之 发送邮箱
  7. POJ 2656
  8. Python爬取 斗图表情,让你成为斗图大佬
  9. Python 模块 和 包
  10. 强烈鄙视那些:自己完全不用android手机,却在做android开发的人