mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-11 06:11:33 +00:00
good good study, day day up!
This commit is contained in:
53
vendor/gopl.io/ch6/urlvalues/main.go
generated
vendored
Normal file
53
vendor/gopl.io/ch6/urlvalues/main.go
generated
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 160.
|
||||
|
||||
// The urlvalues command demonstrates a map type with methods.
|
||||
package main
|
||||
|
||||
/*
|
||||
//!+values
|
||||
package url
|
||||
|
||||
// Values maps a string key to a list of values.
|
||||
type Values map[string][]string
|
||||
|
||||
// Get returns the first value associated with the given key,
|
||||
// or "" if there are none.
|
||||
func (v Values) Get(key string) string {
|
||||
if vs := v[key]; len(vs) > 0 {
|
||||
return vs[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Add adds the value to key.
|
||||
// It appends to any existing values associated with key.
|
||||
func (v Values) Add(key, value string) {
|
||||
v[key] = append(v[key], value)
|
||||
}
|
||||
//!-values
|
||||
*/
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
func main() {
|
||||
//!+main
|
||||
m := url.Values{"lang": {"en"}} // direct construction
|
||||
m.Add("item", "1")
|
||||
m.Add("item", "2")
|
||||
|
||||
fmt.Println(m.Get("lang")) // "en"
|
||||
fmt.Println(m.Get("q")) // ""
|
||||
fmt.Println(m.Get("item")) // "1" (first value)
|
||||
fmt.Println(m["item"]) // "[1 2]" (direct map access)
|
||||
|
||||
m = nil
|
||||
fmt.Println(m.Get("item")) // ""
|
||||
m.Add("item", "3") // panic: assignment to entry in nil map
|
||||
//!-main
|
||||
}
|
Reference in New Issue
Block a user