Golang圣经课后题,一部分是自己写的,一部分是转载的--定时更新

练习 1.1: 修改 echo 程序,使其能够打印 os.Args[0] ,即被执行命令本身的名字

package mainimport ("fmt""os"
)func main() {var s, sep stringfor i := 0; i < len(os.Args); i++ {s += sep + os.Args[i]sep = " "}fmt.Println(s)
}

练习 1.2: 修改 echo 程序,使其打印每个参数的索引和值,每个一行

package mainimport ("fmt""os"
)func main() {for k, arg := range os.Args[0:] {fmt.Println(k, arg)}
}

练习 1.3: 做实验测量潜在低效的版本和使用了 strings.Join 的版本的运行时间差异。(1.6节讲解了部分 time 包,11.4节展示了如何写标准测试程序,以得到系统性的性能评测。)

package mainimport ("strings""testing"
)func BenchmarkString2Join(b *testing.B) {for i := 0; i < b.N; i++ {input := []string{"Welcome", "To", "China"}result := strings.Join(input, " ")if result != "Welcome To China" {b.Error("Unexcepted result:" + result)}}
}func BenchmarkString2Plus(b *testing.B) {for i := 0; i < b.N; i++ {input := []string{"Welcome", "To", "China"}var s, sep stringfor j := 0; j < len(input); j++ {s += sep + input[i]sep = " "}if s != "Welcome To China" {b.Error("Unexcepted result:" + s)}}
}

练习 1.4: 修改 dup2 ,出现重复的行时打印文件名称。

package mainimport ("bufio""fmt""os"
)type LnFile struct {Count     intFilenames []string
}func main() {counts := make(map[string]*LnFile)files := os.Args[1:]if len(files) == 0 {countLines(os.Stdin, counts)} else {for _, arg := range files {f, err := os.Open(arg)if err != nil {fmt.Fprintf(os.Stderr, "dup2:%v\n", err)}countLines(f, counts)f.Close()}}for line, n := range counts {if n.Count > 1 {fmt.Printf("%d %v\n%s\n", n.Count, n.Filenames, line)}}
}func countLines(f *os.File, counts map[string]*LnFile) {input := bufio.NewScanner(f)for input.Scan() {key := input.Text()_, ok := counts[key]if ok {counts[key].Count++counts[key].Filenames = append(counts[key].Filenames, f.Name())} else {counts[key] = new(LnFile)counts[key].Count = 1counts[key].Filenames = append(counts[key].Filenames, f.Name())}}
}

练习 1.5: 修改前面的Lissajous程序里的调色板,由黑色改为绿色。我们可以用 color.RGBA{0xRR, 0xGG, 0xBB, 0xff} 来得到 #RRGGBB 这个色值,三个十六进制的字符串分别代表红、绿、蓝像素。

package mainimport ("image""image/color""image/gif""io""math""math/rand""os"
)var palette = []color.Color{color.RGBA{ 0, 0, 0, 0xFF}, color.RGBA{ 0, 0xFF, 0, 0xFF}}func main() {lissajous(os.Stdout)
}func lissajous(out io.Writer) {const (cycles  = 5    res     = 0.001 size    = 100   nframes = 64    delay   = 8     )freq := rand.Float64() * 3.0 anim := gif.GIF{LoopCount: nframes}phase := 0.0                 for i := 0; i < nframes; i++ {rect := image.Rect(0, 0, 2*size+1, 2*size+1)img := image.NewPaletted(rect, palette)for t := 0.0; t < cycles*2*math.Pi; t += res {x := math.Sin(t)y := math.Sin(t*freq + phase)img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), 1)}phase += 0.1anim.Delay = append(anim.Delay, delay)anim.Image = append(anim.Image, img)}gif.EncodeAll(out, &anim)
}

练习 1.6: 修改Lissajous程序,修改其调色板来生成更丰富的颜色,然后修改SetColorIndex的第三个参数,看看显示结果

package mainimport ("image""image/color""image/gif""io""math""math/rand""os""time"
)const nColors = 10func main() {seed := time.Now()rand.Seed( seed.Unix() )var palette []color.Colorfor i := 0; i < nColors; i++ {r := uint8(rand.Uint32() % 256)g := uint8(rand.Uint32() % 256)b := uint8(rand.Uint32() % 256)palette = append( palette, color.RGBA{ r, g, b, 0xFF} )}lissajous(os.Stdout, palette)
}func lissajous(out io.Writer, palette []color.Color) {const (cycles  = 5res     = 0.001size    = 100nframes = 64delay   = 8)freq := rand.Float64() * 3.0anim := gif.GIF{LoopCount: nframes}phase := 0.0for i := 0; i < nframes; i++ {rect   := image.Rect(0, 0, 2*size+1, 2*size+1)img    := image.NewPaletted(rect, palette)ncolor := uint8(i % len(palette))for t := 0.0; t < cycles*2*math.Pi; t += res {x := math.Sin(t)y := math.Sin(t*freq + phase)img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), ncolor )}phase += 0.1anim.Delay = append(anim.Delay, delay)anim.Image = append(anim.Image, img)}gif.EncodeAll(out, &anim)
}

练习 1.7: 函数调用io.Copy(dst, src)会从src中读取内容,并将读到的结果写入到dst中,使用这个函数替代掉例子中的ioutil.ReadAll来拷贝响应结构体到os.Stdout,避免申请一个缓冲区(例子中的b)来存储。记得处理io.Copy返回结果中的错误

package mainimport ("fmt""io""net/http""os"
)func main() {for _, url := range os.Args[1:] {resp, err := http.Get(url)if err != nil {fmt.Fprintf(os.Stderr, "fetch: %v\n", err)os.Exit(1)}b, err := io.Copy(os.Stdout, resp.Body)resp.Body.Close()if err != nil {fmt.Fprintf(os.Stderr, "fetch: %v\n", err)os.Exit(1)}fmt.Printf("%s", b)}
}

练习 1.8: 修改fetch这个范例,如果输入的url参数没有 http:// 前缀的话,为这个url加上该前缀。你可能会用到strings.HasPrefix这个函数。

package mainimport ("fmt""io""net/http""os""strings"
)func main() {for _, url := range os.Args[1:] {if !strings.HasPrefix(url, "http://") {//url = "http://" + urlurl = strings.Join([]string{"http://", url}, "")}resp, err := http.Get(url)if err != nil {fmt.Fprintf(os.Stderr, "fetch: %v\n", err)os.Exit(1)}b, err := io.Copy(os.Stdout, resp.Body)resp.Body.Close()if err != nil {fmt.Fprintf(os.Stderr, "fetch: %v\n", err)os.Exit(1)}fmt.Printf("%s", b)}
}

练习 1.9: 修改fetch打印出HTTP协议的状态码,可以从resp.Status变量得到该状态码。

package mainimport ("fmt""net/http""os"
)func main() {for _, url := range os.Args[1:] {resp, err := http.Get(url)if err != nil {fmt.Fprintf(os.Stdin, "fetch: %v\n", err)os.Exit(1)}b := resp.Statusfmt.Printf("%s", b)}
}

1.10: 找一个数据量比较大的网站,用本小节中的程序调研网站的缓存策略,对每个URL执行两遍请求,查看两次时间是否有较大的差别,并且每次获取到的响应内容是否一致,修改本节中的程序,将响应结果输出,以便于进行对比。

package mainimport ("fmt""io""io/ioutil""net/http""os""time"
)func main() {start := time.Now()ch := make(chan string)for _, url := range os.Args[1:] {go fetch(url, ch)go fetch(url, ch)}for range os.Args[1:] {fmt.Println(<-ch)fmt.Println(<-ch)}fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
}func fetch(url string, ch chan<- string) {start := time.Now()resp, err := http.Get(url)if err != nil {ch <- fmt.Sprint(err)return}nbytes, err := io.Copy(ioutil.Discard, resp.Body)if err != nil {ch <- fmt.Sprint("while reading %s: %v", url, err)return}secs := time.Since(start).Seconds()ch <- fmt.Sprintf("%.2fs  %7d  %s", secs, nbytes, url)
}

练习 1.12: 修改Lissajour服务,从URL读取变量,比如你可以访问 http://localhost:8000/?cycles=20 这个URL,这样访问可以将程序里的cycles默认的5修改为20。字符串转换为数字可以调用strconv.Atoi函数。你可以在godoc里查看strconv.Atoi的详细说明。

package mainimport ("image""image/color""image/gif""io""math""math/rand""strconv"
)import ("log""net/http""time"
)var palette = []color.Color{color.White, color.Black}const (whiteIndex = 0blackIndex = 1
)type lconfig struct {cycles float64res    float64freq   float64size   intframes intdelay  int
}func main() {rand.Seed(time.Now().UnixNano())lconf := lconfig {cycles  : 5,res     : 0.001,freq    : rand.Float64() * 3.0,size    : 100,frames  : 64,delay   : 8,}http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {confs := r.URL.Query()for i, c := range confs {switch i {case "cycles" : lconf.cycles, _ = strconv.ParseFloat( c[0], 64 )case "freq"   : lconf.freq  , _ = strconv.ParseFloat( c[0], 64 )case "res"    : lconf.res   , _ = strconv.ParseFloat( c[0], 64 )case "size"   : lconf.size  , _ = strconv.Atoi( c[0] )case "frames" : lconf.frames, _ = strconv.Atoi( c[0] )case "delay"  : lconf.delay , _ = strconv.Atoi( c[0] )}}lissajous(w, lconf)})log.Fatal(http.ListenAndServe("localhost:8000", nil))return
}func lissajous(out io.Writer, set lconfig) {anim  := gif.GIF{LoopCount: set.frames}phase := 0.0 // phase differencefor i := 0; i < set.frames; i++ {rect := image.Rect(0, 0, 2*set.size+1, 2*set.size+1)img := image.NewPaletted(rect, palette)for t := 0.0; t < set.cycles*2*math.Pi; t += set.res {x := math.Sin(t)y := math.Sin(t*set.freq + phase)img.SetColorIndex(set.size+int(x*float64(set.size)+0.5), set.size+int(y*float64(set.size)+0.5), blackIndex)}phase += 0.1anim.Delay = append(anim.Delay, set.delay)anim.Image = append(anim.Image, img)}gif.EncodeAll(out, &anim)
}

查看目录

【go语言圣经】练习答案--第一章相关推荐

  1. 第一章c语言基础知识答案,第一章 C语言的基础知识练习题

    第一章 C语言的基础知识练习题 第一章 C语言的基础知识 第一节 对C语言的初步认识 习题 1. 下列叙述中错误的是 B A)任何一个C程序都必须有且仅有一个main函数,C语言总是从main函数开始 ...

  2. c语言基础题库·第一章

    c语言基础题库·第一章 第1章 一.填空题 下列是合法的用户标识符的是( A ). A)_w1 B)3_xy C)int D)LINE-3 2.一个C语言程序是由( B ). A)一个主程序和若干子程 ...

  3. 《机器学习》周志华课后习题答案——第一章(1-3题完结)

    <机器学习>周志华课后习题答案--第一章 文章目录 <机器学习>周志华课后习题答案--第一章 一.表1.1中若只包含编号为1和4的两个样例,试给出相应的版本空间 二.与使用单个 ...

  4. 机器学习_周志华(西瓜书) 课后习题答案 第一章 Chapter1

    机器学习_周志华 课后习题答案 第一章 Chapter1 习题1.1 Q:表1.1中若只包含编号为1和4的两个样例,试给出相应的版本空间. 由所给出的数据集(训练集)可知,属性3个:色泽.根蒂.敲声, ...

  5. c语言程序第一章编程,c语言程序的设计第一章 C语言编程入门.ppt

    c语言程序的设计第一章 C语言编程入门 第1章 C语言编程入门 本章是本书的入门篇,专为初学者熟悉编程过程.掌握程序结构而准备的. 本章学习目标 ? 1)? 能够通过模仿与改变来构造带有测试函数的C语 ...

  6. 《Android移动应用基础教程》(Android Studio)(第二版)黑马教程 课后题答案第一章

    <Android移动应用基础教程>(Android Studio)(第二版)黑马教程 课后题答案 第一章 一.填空题 1.dex 2.@color 3.AndroidManifest.xm ...

  7. 军职在线大学生计算机基础,军职在线演讲与口才答案第一章

    军职在线演讲与口才答案第一章 更多相关问题 下列对材料的认识,正确的是()A.塑料和铝都是很好的绝缘材料B.在各种材料中,铁的导电性能最好C.冰是属于晶 请你按照某一依据对松香.玻璃.铜.铁.沥青进行 ...

  8. 【go语言圣经】习题答案 第一章

    自己写了点gopl的练习题,发个答案大家共勉一下.有问题也请大佬指教. 第一章练习题答案 1.1 1.2 打印命令行参数 1.4 打印重复出现的某行代码及其出现位置 1.5 替换gif图像颜色 1.7 ...

  9. 山西农业大学c语言答案,第一章C语言及程序设计概述-东北农业大学教务处.doc...

    全国高等农林院校"十一五"规划教材 C语言程序设计 孙力 主编 中国农业出版社 内容简介 本书是全国高等农林院校"十一五"规划教材之一. 全书共11章,分别介绍 ...

  10. Java语言程序设计基础篇(第十版)课后习题答案 - 第一章

    第一章:计算机.程序和Java概述 复习题 1.1 什么是硬件和软件? 答:硬件指计算机中可见的物理部分:软件是计算机中看不见的指令,这些指令控制硬件并使硬件完成特定的任务. 1.2 列举计算机的5个 ...

最新文章

  1. mysql 去重con_python 爬虫 实现增量去重和定时爬取实例
  2. Linux下代码运行不了?看这里设置环境变量
  3. AI一分钟 | 小米MIX 2S将于3月27号发布,搭载骁龙845;张朝阳:在研究区块链 但相信AI的力量
  4. 在Filter 无法跳转地址
  5. 没钱还装逼,买二手车的都是什么人?
  6. fpga初始化错误_一种SRAM型FPGA单粒子效应加固平台设计
  7. C++成员函数指针的另类调用方法
  8. [蓝桥杯][2014年第五届真题]排列序数(思维)
  9. 轻量级ORM《sqlcommon》第一个版本发布了
  10. WPF中ContextMenu(右键菜单)使用Command在部分控件上默认为灰色的处理方法
  11. 200多个新颖独特的域名展示
  12. Grafana全面瓦解
  13. 机器人植入情感芯片利与弊_马斯克活猪脑机接口试验成功!多芯片植入,硬币大小,实时读取脑电波,已被批准人脑实验...
  14. BX+CX+loop
  15. Rosenbrock函数的梯度与海瑟矩阵
  16. 【UWB】UWB基本定位原理
  17. AMESim储能电气库用户手册(二)
  18. 多平台聚合关键字搜索
  19. RHEL8.x-RedHat-Podman
  20. wordpress 漂亮的Cosy主题

热门文章

  1. springboot的使用!
  2. linux应用商店下载的程序,利用抓包工具从Windows 10 应用商店里下载各种离线应用...
  3. iQOO 8实测上手体验:王者归来,从不高调
  4. 小白的爬虫--微博版
  5. 编译原理MOOC部分习题答案+解读(逐渐更新..
  6. win10防火墙删除的文件在哪里_Win10系统瘦身指南:删除C盘这些文件,让你的电脑秒变新机!...
  7. Alamofire源码分析
  8. [3D动画][材质]
  9. 如何入门黑客技术,黑客技术入门该学什么?
  10. 路由器端口镜像含义与镜像配置