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