6.3. 通過嵌入結構體來擴展類型

gopl.io/ch6/coloredpoint
import "image/color"
type Point struct{ X, Y float64 }
type ColoredPoint struct {
Point
Color color.RGBA
}


var cp ColoredPoint
cp.X = 1
fmt.Println(cp.Point.X) // "1"
cp.Point.Y = 2
fmt.Println(cp.Y) // "2"


red := color.RGBA{255, 0, 0, 255}
blue := color.RGBA{0, 0, 255, 255}
var p = ColoredPoint{Point{1, 1}, red}
var q = ColoredPoint{Point{5, 4}, blue}
fmt.Println(p.Distance(q.Point)) // "5"
p.ScaleBy(2)
q.ScaleBy(2)
fmt.Println(p.Distance(q.Point)) // "10"


Point類的方法也被引入了ColoredPoint。用這種方式，內嵌可以使我們定義字段特别多的複雜類型，我們可以將字段先按小類型分組，然後定義小類型的方法，之後再把它們組合起來。

p.Distance(q) // compile error: cannot use q (ColoredPoint) as Point


func (p ColoredPoint) Distance(q Point) float64 {
return p.Point.Distance(q)
}

func (p *ColoredPoint) ScaleBy(factor float64) {
p.Point.ScaleBy(factor)
}


type ColoredPoint struct {
*Point
Color color.RGBA
}

p := ColoredPoint{&Point{1, 1}, red}
q := ColoredPoint{&Point{5, 4}, blue}
fmt.Println(p.Distance(*q.Point)) // "5"
q.Point = p.Point                 // p and q now share the same Point
p.ScaleBy(2)
fmt.Println(*p.Point, *q.Point) // "{2 2} {2 2}"


type ColoredPoint struct {
Point
color.RGBA
}


var (
mu sync.Mutex // guards mapping
mapping = make(map[string]string)
)

func Lookup(key string) string {
mu.Lock()
v := mapping[key]
mu.Unlock()
return v
}


var cache = struct {
sync.Mutex
mapping map[string]string
}{
mapping: make(map[string]string),
}

func Lookup(key string) string {
cache.Lock()
v := cache.mapping[key]
cache.Unlock()
return v
}