ch7: fix code format

This commit is contained in:
chai2010
2016-01-21 10:22:10 +08:00
parent 2420954025
commit 0b5ec941ed
13 changed files with 208 additions and 186 deletions

View File

@@ -8,6 +8,7 @@
``` go
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...)
@@ -26,6 +27,7 @@ Fprintf的前綴F表示文件(File)也表明格式化輸出結果應該被寫入
``` go
package io
// 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.
@@ -45,21 +47,23 @@ io.Writer類型定義了函數Fprintf和這個函數調用者之間的約定。
讓我們通過一個新的類型來進行校驗,下面\*ByteCounter類型里的Write方法僅僅在丟失寫向它的字節前統計它們的長度。(在這個+=賦值語句中讓len(p)的類型和\*c的類型匹配的轉換是必須的。)
<u><i>gopl.io/ch7/bytecounter</i></u>
```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
*c += ByteCounter(len(p)) // convert int to ByteCounter
return len(p), nil
}
```
因爲*ByteCounter滿足io.Writer的約定我們可以把它傳入Fprintf函數中Fprintf函數執行字符串格式化的過程不會去關註ByteCounter正確的纍加結果的長度。
```go
var c ByteCounter
c.Write([]byte("hello"))
fmt.Println(c) // "5", = len("hello")
c = 0 // reset the counter
c = 0 // reset the counter
var name = "Dolly"
fmt.Fprintf(&c, "hello, %s", name)
fmt.Println(c) // "12", = len("hello, Dolly")
@@ -69,11 +73,12 @@ fmt.Println(c) // "12", = len("hello, Dolly")
```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
String() string
}
```