## 6.2. 基於指針對象的方法

func (p *Point) ScaleBy(factor float64) {
p.X *= factor
p.Y *= factor
}


type P *int
func (P) f() { /* ... */ } // compile error: invalid receiver type


r := &Point{1, 2}
r.ScaleBy(2)
fmt.Println(*r) // "{2, 4}"


p := Point{1, 2}
pptr := &p
pptr.ScaleBy(2)
fmt.Println(p) // "{2, 4}"


p := Point{1, 2}
(&p).ScaleBy(2)
fmt.Println(p) // "{2, 4}"


p.ScaleBy(2)


Point{1, 2}.ScaleBy(2) // compile error: can't take address of Point literal


pptr.Distance(q)
(*pptr).Distance(q)


Point{1, 2}.Distance(q) //  Point
pptr.ScaleBy(2)         // *Point


p.ScaleBy(2) // implicit (&p)


pptr.Distance(q) // implicit (*pptr)


### 6.2.1. Nil也是一個合法的接收器類型

// An IntList is a linked list of integers.
// A nil *IntList represents the empty list.
type IntList struct {
Value int
Tail  *IntList
}
// Sum returns the sum of the list elements.
func (list *IntList) Sum() int {
if list == nil {
return 0
}
return list.Value + list.Tail.Sum()
}


net/url
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)
}


gopl.io/ch6/urlvalues
m := url.Values{"lang": {"en"}} // direct construction

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