[日常] Go语言圣经-函数多返回值习题
2023-02-18 15:41:37 时间
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。
这个很简单就不贴了
相关文章
- linux系统上国际化失败
- 修改git仓库的远程地址
- 痞子衡嵌入式:在i.MXRT启动头FDCB里调整Flash工作频率也需同步设Dummy Cycle (以IS25WP128为例)
- 《痞子衡嵌入式半月刊》 第 29 期
- 痞子衡嵌入式:从头开始认识i.MXRT启动头FDCB里的lookupTable
- git为单独的仓库设置提交的用户名
- 痞子衡嵌入式:MCUXpresso IDE下在线调试时使用不同复位策略的现象总结
- window系统上实现mongodb副本集的搭建
- 痞子衡嵌入式:关于恩智浦入驻B站的一些思考
- mongodb的索引操作
- 《痞子衡嵌入式半月刊》 第 28 期
- mongodb的聚合操作
- 痞子衡嵌入式:分享一个i.MXRT系列配套DRAM压力测试上位机工具(i.MXRT DRAM Tester)
- mongodb的简单查询
- 痞子衡嵌入式:在i.MXRT1060-EVK上利用memtester程序给SDRAM做压力测试
- 痞子衡嵌入式:内存读写正确性压力测试程序(memtester)
- 对mongo文档的增删改操作
- 痞子衡嵌入式:盘点国内MCU级RISC-V内核IP厂商
- 《痞子衡嵌入式半月刊》 第 27 期
- 痞子衡嵌入式:盘点国内车规级MCU厂商(2020年及之前发布产品)