mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-12-20 12:44:20 +08:00
fmr code
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
## 6.3. 通過嵌入結構體來擴展類型
|
||||
|
||||
來看看ColoredPoint這個類型:
|
||||
|
||||
```go
|
||||
gopl.io/ch6/coloredpoint
|
||||
import "image/color"
|
||||
@@ -33,6 +34,7 @@ p.ScaleBy(2)
|
||||
q.ScaleBy(2)
|
||||
fmt.Println(p.Distance(q.Point)) // "10"
|
||||
```
|
||||
|
||||
Point類的方法也被引入了ColoredPoint。用這種方式,內嵌可以使我們定義字段特别多的複雜類型,我們可以將字段先按小類型分組,然後定義小類型的方法,之後再把它們組合起來。
|
||||
|
||||
讀者如果對基於類來實現面向對象的語言比較熟悉的話,可能會傾向於將Point看作一個基類,而ColoredPoint看作其子類或者繼承類,或者將ColoredPoint看作"is a" Point類型。但這是錯誤的理解。請註意上面例子中對Distance方法的調用。Distance有一個參數是Point類型,但q併不是一個Point類,所以盡管q有着Point這個內嵌類型,我們也必鬚要顯式地選擇它。嚐試直接傳q的話你會看到下面這樣的錯誤:
|
||||
@@ -72,6 +74,7 @@ fmt.Println(*p.Point, *q.Point) // "{2 2} {2 2}"
|
||||
```
|
||||
|
||||
一個struct類型也可能會有多個匿名字段。我們將ColoredPoint定義爲下面這樣:
|
||||
|
||||
```go
|
||||
type ColoredPoint struct {
|
||||
Point
|
||||
@@ -118,6 +121,3 @@ func Lookup(key string) string {
|
||||
```
|
||||
|
||||
我們給新的變量起了一個更具表達性的名字:cache。因爲sync.Mutex字段也被嵌入到了這個struct里,其Lock和Unlock方法也就都被引入到了這個匿名結構中了,這讓我們能夠以一個簡單明了的語法來對其進行加鎖解鎖操作。
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user