mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2024-11-28 17:19:06 +00:00
36 lines
696 B
Go
36 lines
696 B
Go
|
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||
|
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||
|
|
||
|
// See page 173.
|
||
|
|
||
|
// Bytecounter demonstrates an implementation of io.Writer that counts bytes.
|
||
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
)
|
||
|
|
||
|
//!+bytecounter
|
||
|
|
||
|
type ByteCounter int
|
||
|
|
||
|
func (c *ByteCounter) Write(p []byte) (int, error) {
|
||
|
*c += ByteCounter(len(p)) // convert int to ByteCounter
|
||
|
return len(p), nil
|
||
|
}
|
||
|
|
||
|
//!-bytecounter
|
||
|
|
||
|
func main() {
|
||
|
//!+main
|
||
|
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")
|
||
|
//!-main
|
||
|
}
|