// Dup1 prints the text of each line that appears more than // once in the standard input, preceded by its count. package main
import ( "bufio" "fmt" "os" )
funcmain() { counts := make(map[string]int) input := bufio.NewScanner(os.Stdin) for input.Scan() { counts[input.Text()]++ } // NOTE: ignoring potential errors from input.Err() for line, n := range counts { if n > 1 { fmt.Printf("%d\t%s\n", n, line) } } }
IF语句
if语句条件两边也不加括号,但是主体部分需要加
if语句的else部分是可选的,在if的条件为false时执行。
map
map存储了键/值(key/value)的集合,对集合元素,提供常数时间的存、取或测试操作。
键可以是任意类型,只要其值能用==运算符比较,最常见的例子是字符串
值则可以是任意类型。这个例子中的键是字符串,值是整数
从功能和实现上说,Go的map类似于Java语言中的HashMap,Python语言中的dict
map的迭代顺序并不确定,从实践来看,该顺序随机,每次运行都会变化。
这种设计是有意为之的,因为能防止程序依赖特定遍历顺序,而这是无法保证的。
每次读取一行输入,该行被当做键存入map,其对应的值递增。
counts[input.Text()]++语句等价下面两句:
1 2
line := input.Text() counts[line] = counts[line] + 1
funcmain() { counts := make(map[string]int) for _, filename := range os.Args[1:] { data, err := ioutil.ReadFile(filename) if err != nil { fmt.Fprintf(os.Stderr, "dup3: %v\n", err) continue } for _, line := range strings.Split(string(data), "\n") { counts[line]++ } } for line, n := range counts { if n > 1 { fmt.Printf("%d\t%s\n", n, line) } } }
var palette = []color.Color{color.White, color.Black}
const ( whiteIndex = 0// first color in palette blackIndex = 1// next color in palette )
funcmain() { // The sequence of images is deterministic unless we seed // the pseudo-random number generator using the current time. // Thanks to Randall McPherson for pointing out the omission. rand.Seed(time.Now().UTC().UnixNano()) lissajous(os.Stdout) }
funclissajous(out io.Writer) { const ( cycles = 5// number of complete x oscillator revolutions res = 0.001// angular resolution size = 100// image canvas covers [-size..+size] nframes = 64// number of animation frames delay = 8// delay between frames in 10ms units )
freq := rand.Float64() * 3.0// relative frequency of y oscillator anim := gif.GIF{LoopCount: nframes} phase := 0.0// phase difference 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), blackIndex) } phase += 0.1 anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors }
// handler echoes the Path component of the request URL r. funchandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path) }
// handler echoes the Path component of the requested URL. funchandler(w http.ResponseWriter, r *http.Request) { mu.Lock() count++ mu.Unlock() fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path) }
// counter echoes the number of calls so far. funccounter(w http.ResponseWriter, r *http.Request) { mu.Lock() fmt.Fprintf(w, "Count %d\n", count) mu.Unlock() }
handler函数会把请求的http头和请求的form数据都打印出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// handler echoes the HTTP request. funchandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto) for k, v := range r.Header { fmt.Fprintf(w, "Header[%q] = %q\n", k, v) } fmt.Fprintf(w, "Host = %q\n", r.Host) fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr) if err := r.ParseForm(); err != nil { log.Print(err) } for k, v := range r.Form { fmt.Fprintf(w, "Form[%q] = %q\n", k, v) } }
// handler echoes the Path component of the requested URL. // handler echoes the HTTP request. funchandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto) for k, v := range r.Header { fmt.Fprintf(w, "Header[%q] = %q\n", k, v) } fmt.Fprintf(w, "Host = %q\n", r.Host) fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr) if err := r.ParseForm(); err != nil { log.Print(err) } for k, v := range r.Form { fmt.Fprintf(w, "Form[%q] = %q\n", k, v) } }
// counter echoes the number of calls so far. funccounter(w http.ResponseWriter, r *http.Request) { mu.Lock() fmt.Fprintf(w, "Count %d\n", count) mu.Unlock() }
// Lissajous generates GIF animations of random Lissajous figures.
var palette = []color.Color{color.White, color.Black}
const ( whiteIndex = 0// first color in palette blackIndex = 1// next color in palette )
funclissajous(out io.Writer) { const ( cycles = 5// number of complete x oscillator revolutions res = 0.001// angular resolution size = 100// image canvas covers [-size..+size] nframes = 64// number of animation frames delay = 8// delay between frames in 10ms units )
freq := rand.Float64() * 3.0// relative frequency of y oscillator anim := gif.GIF{LoopCount: nframes} phase := 0.0// phase difference 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), blackIndex) } phase += 0.1 anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors }