mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-13 15:12:32 +00:00
good good study, day day up!
This commit is contained in:
35
vendor/gopl.io/ch7/bytecounter/main.go
generated
vendored
Normal file
35
vendor/gopl.io/ch7/bytecounter/main.go
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
// 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
|
||||
}
|
Reference in New Issue
Block a user