mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-12-20 12:44:20 +08:00
ch6: fix code format
This commit is contained in:
@@ -2,13 +2,15 @@
|
||||
|
||||
來看看ColoredPoint這個類型:
|
||||
|
||||
<u><i>gopl.io/ch6/coloredpoint</i></u>
|
||||
```go
|
||||
gopl.io/ch6/coloredpoint
|
||||
import "image/color"
|
||||
|
||||
type Point struct{ X, Y float64 }
|
||||
|
||||
type ColoredPoint struct {
|
||||
Point
|
||||
Color color.RGBA
|
||||
Point
|
||||
Color color.RGBA
|
||||
}
|
||||
```
|
||||
|
||||
@@ -47,11 +49,11 @@ p.Distance(q) // compile error: cannot use q (ColoredPoint) as Point
|
||||
|
||||
```go
|
||||
func (p ColoredPoint) Distance(q Point) float64 {
|
||||
return p.Point.Distance(q)
|
||||
return p.Point.Distance(q)
|
||||
}
|
||||
|
||||
func (p *ColoredPoint) ScaleBy(factor float64) {
|
||||
p.Point.ScaleBy(factor)
|
||||
p.Point.ScaleBy(factor)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -61,8 +63,8 @@ func (p *ColoredPoint) ScaleBy(factor float64) {
|
||||
|
||||
```go
|
||||
type ColoredPoint struct {
|
||||
*Point
|
||||
Color color.RGBA
|
||||
*Point
|
||||
Color color.RGBA
|
||||
}
|
||||
|
||||
p := ColoredPoint{&Point{1, 1}, red}
|
||||
@@ -77,10 +79,11 @@ fmt.Println(*p.Point, *q.Point) // "{2 2} {2 2}"
|
||||
|
||||
```go
|
||||
type ColoredPoint struct {
|
||||
Point
|
||||
color.RGBA
|
||||
Point
|
||||
color.RGBA
|
||||
}
|
||||
```
|
||||
|
||||
然後這種類型的值便會擁有Point和RGBA類型的所有方法,以及直接定義在ColoredPoint中的方法。當編譯器解析一個選擇器到方法時,比如p.ScaleBy,它會首先去找直接定義在這個類型里的ScaleBy方法,然後找被ColoredPoint的內嵌字段們引入的方法,然後去找Point和RGBA的內嵌字段引入的方法,然後一直遞歸向下找。如果選擇器有二義性的話編譯器會報錯,比如你在同一級里有兩個同名的方法。
|
||||
|
||||
方法隻能在命名類型(像Point)或者指向類型的指針上定義,但是多虧了內嵌,有些時候我們給匿名struct類型來定義方法也有了手段。
|
||||
@@ -89,15 +92,15 @@ type ColoredPoint struct {
|
||||
|
||||
```go
|
||||
var (
|
||||
mu sync.Mutex // guards mapping
|
||||
mapping = make(map[string]string)
|
||||
mu sync.Mutex // guards mapping
|
||||
mapping = make(map[string]string)
|
||||
)
|
||||
|
||||
func Lookup(key string) string {
|
||||
mu.Lock()
|
||||
v := mapping[key]
|
||||
mu.Unlock()
|
||||
return v
|
||||
mu.Lock()
|
||||
v := mapping[key]
|
||||
mu.Unlock()
|
||||
return v
|
||||
}
|
||||
```
|
||||
|
||||
@@ -105,18 +108,18 @@ func Lookup(key string) string {
|
||||
|
||||
```go
|
||||
var cache = struct {
|
||||
sync.Mutex
|
||||
mapping map[string]string
|
||||
sync.Mutex
|
||||
mapping map[string]string
|
||||
}{
|
||||
mapping: make(map[string]string),
|
||||
mapping: make(map[string]string),
|
||||
}
|
||||
|
||||
|
||||
func Lookup(key string) string {
|
||||
cache.Lock()
|
||||
v := cache.mapping[key]
|
||||
cache.Unlock()
|
||||
return v
|
||||
cache.Lock()
|
||||
v := cache.mapping[key]
|
||||
cache.Unlock()
|
||||
return v
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user