练习 1.1 : 修改echo程序,使其能够打印os.Args[0],即被执行命令本身的名字。
package main
import (
"fmt"
"strings"
"os"
)
func main() {
fmt.Println(strings.Join(os.Args[:]," "))
}
练习 1.2: 修改echo程序,使其打印每个参数的索引和值,每个一行。
package main
import (
"os"
"fmt"
)
func main() {
for index,arg := range os.Args[1:]{
fmt.Println(index+1,":",arg)
}
}
练习 1.3: 做实验测量潜在低效的版本和使用了strings.Join的版本的运行时间差异
package main
import (
"time"
"os"
"fmt"
"strings"
)
func main() {
joinEcho()
plusEcho()
}
func joinEcho(){
start := time.Now();
fmt.Println(strings.Join(os.Args[1:]," "))
fmt.Printf("echo2: %fs\n",time.Since(start).Seconds())
}
func plusEcho(){
start := time.Now()
s,sep := "",""
for _,arg := range os.Args[1:]{
s += sep + arg
sep = " "
}
fmt.Println(s)
fmt.Printf("plushEcho: %fs\n",time.Since(start).Seconds())
}
练习 1.4: 修改dup2,出现重复的行时打印文件名称。
package main
import (
"os"
"bufio"
"fmt"
)
func main() {
counts := make(map[string]int)
fileNames := make(map[string][]string)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin,counts,fileNames)
}else{
for _,file := range files {
f, e := os.Open(file)
if e != nil {
fmt.Fprintf(os.Stderr,"dup : %v\n",e)
continue
}
countLines(f,counts,fileNames)
f.Close()
}
}
for line,n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\t%s\n",n,line,fileNames[line])
}
}
}
func countLines(f *os.File,counts map[string]int,filenames map[string][]string){
input := bufio.NewScanner(f)
for input.Scan(){
line := input.Text()
counts[line]++
if !contains(filenames[line],f.Name()){
filenames[line] = append(filenames[line],f.Name())
}
}
}
func contains(names []string,target string) bool {
for _,v := range names {
if v == target {
return true
}
}
return false
}
练习 1.5: 修改前面的Lissajous程序里的调色板,由黑色改为绿色。我们可以用color.RGBA{0xRR, 0xGG, 0xBB, 0xff}来得到#RRGGBB这个色值,三个十六进制的字符串分别代表红、绿、蓝像素。
// Lissajous generates GIF animations of random Lissajous figures
package main
import (
"image/color"
"math/rand"
"time"
"io"
"image/gif"
"image"
"math"
"os"
"net/http"
"log"
)
var green = color.RGBA{0x00,0xff,0x00,0xff}
var palette = []color.Color{color.Black,green}
const(
blackIndex = 0 //first color in palette
greenIndex = 1 //next color in palette
)
func lissajous(out io.Writer){
const (
cycles = 5 // number of complete x oscillator revolutions
res = 0.001 // angular resolution

本文提供了一系列Go语言编程实践案例,包括命令行参数处理、文件处理、网络请求、图像动画生成等,通过具体示例帮助读者深入理解Go语言的特性。
最低0.47元/天 解锁文章
328





