linehk / gopl

gopl(The Go Programming Language) is a project that contains all the sample code and all exercise answers in the Go Programming Language.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ch7-ex7.1中为什么是len(p) 而不是c呢

wei98k opened this issue · comments

type WordCounter int
func (c *WordCounter) Write(p []byte) (int, error) {
scanner := bufio.NewScanner(bytes.NewReader(p))
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
*c++
}
return len(p), nil
}

题目是这样的,练习 7.1:使用来自 ByteCounter 的思路,实现一个针对单词和行数的计数器。你会发现 bufio.ScanWords 非常的有用。

书里面的 ByteCounter 如下:

type ByteCounter int

func (c *ByteCounter) Write(p []byte) (int, error) {
	*c += ByteCounter(len(p)) // convert int to ByteCounter
	return len(p), nil
}

它也是返回的 len(p)。

c 的底层数据类型为 int,返回 len(c) 会发生错误:./prog.go:29:12: invalid argument c (type *WordCounter) for len