This commit is contained in:
chai2010
2015-12-21 17:25:03 +08:00
parent 38e249c65a
commit f699e83e46
6 changed files with 45 additions and 42 deletions

View File

@@ -9,12 +9,12 @@
package fmt
func Fprintf(w io.Writer, format string, args ...interface{}) (int, error)
func Printf(format string, args ...interface{}) (int, error) {
return Fprintf(os.Stdout, format, args...)
return Fprintf(os.Stdout, format, args...)
}
func Sprintf(format string, args ...interface{}) string {
var buf bytes.Buffer
Fprintf(&buf, format, args...)
return buf.String()
var buf bytes.Buffer
Fprintf(&buf, format, args...)
return buf.String()
}
```
Fprintf的前綴F表示文件(File)也表明格式化輸齣結果應該被寫入第一個參數提供的文件中。在Printf函數中的第一個參數os.Stdout是*os.File類型在Sprintf函數中的第一個參數&buf是一個指向可以寫入字節的內存緩衝區然而它
@@ -23,17 +23,17 @@ Fprintf的前綴F表示文件(File)也表明格式化輸齣結果應該被寫入
卽使Fprintf函數中的第一個參數也不是一個文件類型。它是io.Writer類型這是一個接口類型定義如下
``` go
package io
// Writer is the interface that wraps the basic Write method.
type Writer interface {
// 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)
}
// 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)
```
io.Writer類型定義了函數Fprintf和這個函數調用者之間的約定。一方面這個約定需要調用者提供具體類型的值就像\*os.File和\*bytes.Buffer這些類型都有一個特定籤名和行爲的Write的函數。另一方面這個約定保證了Fprintf接受任何滿足io.Writer接口的值都可以工作。Fprintf函數可能沒有假定寫入的是一個文件或是一段內存而是寫入一個可以調用Write函數的值。