前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[日常] Go语言圣经-函数多返回值习题

[日常] Go语言圣经-函数多返回值习题

作者头像
唯一Chat
发布2019-09-10 12:30:45
7900
发布2019-09-10 12:30:45
举报
文章被收录于专栏:陶士涵的菜地陶士涵的菜地

Go语言圣经-函数多返回值 1.在Go中,一个函数可以返回多个值 2.许多标准库中的函数返回2个值,一个是期望得到的返回值,另一个是函数出错时的错误信息 3.如果一个函数将所有的返回值都显示的变量名,那么该函数的return语句可以省略操作数。这称之为bare return。

练习 5.5: 实现countWordsAndImages。(参考练习4.9如何分词)

代码语言:javascript
复制
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。 这个很简单就不贴了

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档