《Go语言圣经》第一章
1.1 修改
echo
程序,使其能够打印os.Args[0]
,即被执行命令本身的名字。
package main
import (
"fmt"
"os"
)
func main() {
var s,sep string
for i := 0;i < len(os.Args);i ++{
s += sep + os.Args[i]
sep = " "
}
fmt.Println(s)
}
1.2 修改
echo
程序,使其打印每个参数的索引和值,每个一行。
package main
import (
"fmt"
"os"
)
func main() {
for k,v := range os.Args{
fmt.Println(k,v)
}
}
1.3 做实验测量潜在低效的版本和使用了
strings.Join
的版本的运行时间差异。
1.4 修改dup2,出现重复的行时打印文件名称。
import ( "bufio" "fmt" "os" ) func main() { counts := make(map[string]int) filenames := make(map[string][]string) files := os.Args[1:] if len(files) == 0 { countLine(os.Stdin,counts,filenames) }else { for _,arg := range files{ f, err := os.Open(arg) if err != nil { fmt.Fprintf(os.Stderr,"dup2%v\n",err) continue } countLine(f,counts,filenames) f.Close() } } for line,count := range counts{ if count > 1 { fmt.Println(line,count,filenames[line]) } } } func countLine(file *os.File, counts map[string]int,filenames map[string][]string) { input := bufio.NewScanner(file) for input.Scan() { line := input.Text() counts[line] ++ filenames[line] = append(filenames[line], file.Name()) } }
修改前面的Lissajous程序里的调色板,由黑色改为绿色。我们可以用color.RGBA{0xRR, 0xGG, 0xBB, 0xff}来得到#RRGGBB这个色值,三个十六进制的字符串分别代表红、绿、蓝像素。
package main import ( "image" "image/color" "image/gif" "io" "math" "math/rand" "os" "time" ) var palette = []color.Color{color.White,color.RGBA{0,0xff,0,0Xff}} const( whiteIndex = 0 blackIndex = 1 ) func main() { rand.Seed(time.Now().UTC().UnixNano()) lissajous(os.Stdout) } func lissajous(out io.Writer) { const( cycle = 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 < cycle*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),blackIndex) } phase += 0.1 anim.Delay = append(anim.Delay,delay) anim.Image = append(anim.Image,img) } gif.EncodeAll(out,&anim) }
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: