gopl-zh.github.com/ch7/ch7-01.md

91 lines
5.7 KiB
Markdown
Raw Normal View History

2015-12-09 07:45:11 +00:00
## 7.1. 接口約定
2015-12-26 12:05:30 +00:00
目前爲止,我們看到的類型都是具體的類型。一個具體的類型可以準確的描述它所代表的值併且展示出對類型本身的一些操作方式就像數字類型的算術操作,切片類型的索引、附加和取范圍操作。具體的類型還可以通過它的方法提供額外的行爲操作。總的來説,當你拿到一個具體的類型時你就知道它的本身是什麽和你可以用它來做什麽。
2015-12-09 07:45:11 +00:00
2015-12-26 12:05:30 +00:00
在Go語言中還存在着另外一種類型接口類型。接口類型是一種抽象的類型。它不會暴露出它所代表的對象的內部值的結構和這個對象支持的基礎操作的集合它們隻會展示出它們自己的方法。也就是説當你有看到一個接口類型的值時你不知道它是什麽唯一知道的就是可以通過它的方法來做什麽。
2015-12-09 07:45:11 +00:00
2015-12-26 12:05:30 +00:00
在本書中我們一直使用兩個相似的函數來進行字符串的格式化fmt.Printf它會把結果寫到標準輸出和fmt.Sprintf它會把結果以字符串的形式返迴。得益於使用接口我們不必可悲的因爲返迴結果在使用方式上的一些淺顯不同就必需把格式化這個最睏難的過程複製一份。實際上這兩個函數都使用了另一個函數fmt.Fprintf來進行封裝。fmt.Fprintf這個函數對它的計算結果會被怎麽使用是完全不知道的。
2016-01-02 13:17:21 +00:00
2015-12-09 07:45:11 +00:00
``` go
package fmt
func Fprintf(w io.Writer, format string, args ...interface{}) (int, error)
func Printf(format string, args ...interface{}) (int, error) {
2015-12-21 09:25:03 +00:00
return Fprintf(os.Stdout, format, args...)
2015-12-09 07:45:11 +00:00
}
func Sprintf(format string, args ...interface{}) string {
2015-12-21 09:25:03 +00:00
var buf bytes.Buffer
Fprintf(&buf, format, args...)
return buf.String()
2015-12-09 07:45:11 +00:00
}
```
2016-01-02 13:17:21 +00:00
2015-12-26 12:05:30 +00:00
Fprintf的前綴F表示文件(File)也表明格式化輸出結果應該被寫入第一個參數提供的文件中。在Printf函數中的第一個參數os.Stdout是*os.File類型在Sprintf函數中的第一個參數&buf是一個指向可以寫入字節的內存緩衝區然而它
2015-12-18 06:49:31 +00:00
併不是一個文件類型盡管它在某種意義上和文件類型相似。
2015-12-09 07:45:11 +00:00
卽使Fprintf函數中的第一個參數也不是一個文件類型。它是io.Writer類型這是一個接口類型定義如下
2016-01-02 13:17:21 +00:00
2015-12-09 07:45:11 +00:00
``` go
package io
2015-12-21 09:25:03 +00:00
// Writer is the interface that wraps the basic Write method.
type Writer interface {
// Write writes len(p) bytes from p to the underlying data stream.
// It returns the number of bytes written from p (0 <= n <= len(p))
// and any error encountered that caused the write to stop early.
// Write must return a non-nil error if it returns n < len(p).
// Write must not modify the slice data, even temporarily.
//
// Implementations must not retain p.
Write(p []byte) (n int, err error)
2015-12-09 07:45:11 +00:00
}
```
2015-12-18 06:49:31 +00:00
io.Writer類型定義了函數Fprintf和這個函數調用者之間的約定。一方面這個約定需要調用者提供具體類型的值就像\*os.File和\*bytes.Buffer這些類型都有一個特定籤名和行爲的Write的函數。另一方面這個約定保證了Fprintf接受任何滿足io.Writer接口的值都可以工作。Fprintf函數可能沒有假定寫入的是一個文件或是一段內存而是寫入一個可以調用Write函數的值。
2015-12-09 07:45:11 +00:00
2015-12-18 06:49:31 +00:00
因爲fmt.Fprintf函數沒有對具體操作的值做任何假設而是僅僅通過io.Writer接口的約定來保證行爲所以第一個參數可以安全地傳入一個任何具體類型的值隻需要滿足io.Writer接口。一個類型可以自由的使用另一個滿足相同接口的類型來進行替換被稱作可替換性(LSP里氏替換)。這是一個面向對象的特徵。
2015-12-09 07:45:11 +00:00
2016-01-18 03:22:04 +00:00
讓我們通過一個新的類型來進行校驗,下面\*ByteCounter類型里的Write方法僅僅在丟失寫向它的字節前統計它們的長度。(在這個+=賦值語句中讓len(p)的類型和\*c的類型匹配的轉換是必須的。)
2016-01-02 13:17:21 +00:00
2015-12-09 07:45:11 +00:00
```go
// gopl.io/ch7/bytecounter
type ByteCounter int
func (c *ByteCounter) Write(p []byte) (int, error) {
*c += ByteCounter(len(p)) // convert int to ByteCounter
return len(p), nil
}
```
2015-12-18 02:53:03 +00:00
因爲*ByteCounter滿足io.Writer的約定我們可以把它傳入Fprintf函數中Fprintf函數執行字符串格式化的過程不會去關註ByteCounter正確的纍加結果的長度。
2016-01-02 13:17:21 +00:00
2015-12-09 07:45:11 +00:00
```go
var c ByteCounter
c.Write([]byte("hello"))
fmt.Println(c) // "5", = len("hello")
c = 0 // reset the counter
var name = "Dolly"
fmt.Fprintf(&c, "hello, %s", name)
fmt.Println(c) // "12", = len("hello, Dolly")
```
2016-01-02 13:17:21 +00:00
2015-12-26 12:05:30 +00:00
除了io.Writer這個接口類型還有另一個對fmt包很重要的接口類型。Fprintf和Fprintln函數向類型提供了一種控製它們值輸出的途徑。在2.5節中我們爲Celsius類型提供了一個String方法以便於可以打印成這樣"100°C" 在6.5節中我們給*IntSet添加一個String方法這樣集合可以用傳統的符號來進行表示就像"{1 2 3}"。給一個類型定義String方法可以讓它滿足最廣泛使用之一的接口類型fmt.Stringer
2016-01-02 13:17:21 +00:00
2015-12-09 07:45:11 +00:00
```go
package fmt
// The String method is used to print values passed
// as an operand to any format that accepts a string
// or to an unformatted printer such as Print.
type Stringer interface {
String() string
}
```
2016-01-02 13:17:21 +00:00
2015-12-18 02:53:03 +00:00
我們會在7.10節解釋fmt包怎麽發現哪些值是滿足這個接口類型的。
2015-12-09 07:45:11 +00:00
2016-01-18 03:14:19 +00:00
**練習 7.1** 使用來自ByteCounter的思路實現一個針對對單詞和行數的計數器。你會發現bufio.ScanWords非常的有用。
2015-12-09 07:45:11 +00:00
2016-01-18 03:14:19 +00:00
**練習 7.2** 寫一個帶有如下函數籤名的函數CountingWriter傳入一個io.Writer接口類型返迴一個新的Writer類型把原來的Writer封裝在里面和一個表示寫入新的Writer字節數的int64類型指針
2016-01-02 13:17:21 +00:00
2015-12-09 07:45:11 +00:00
```go
func CountingWriter(w io.Writer) (io.Writer, *int64)
```
2016-01-02 13:17:21 +00:00
2016-01-18 03:14:19 +00:00
**練習 7.3** 爲在gopl.io/ch4/treesort (§4.4)的*tree類型實現一個String方法去展示tree類型的值序列。