Go language bible-interface
1. An interface type is an abstraction and generalization of the behavior of other types
2. The uniqueness of an interface type in the Go language is that it satisfies the implicit implementation
3. There is another type in the Go language: Interface Type. An interface type is an abstract type
4. A type can be freely replaced by another type that satisfies the same interface is called substitutability (LSP Liskov substitution)
Exercise 7.1: Using ideas from ByteCounter, implement a counter for word and line counts. You will find bufio.ScanWords very useful.
package main import ( "bufio" "fmt" "strings" ) func main() { var c WordsCounter fmt.Fprintf(&c, "hello world 123") fmt.Println(c) //output 3 } /* Exercise 7.1: Using ideas from ByteCounter, implement a counter for word and line counts. You will find bufio.ScanWords very useful. */ type ByteCounter int func (c *ByteCounter) Write(p []byte) (int, error) { *c += ByteCounter(len(p)) // convert int to ByteCounter return len(p), nil } //define the type type WordsCounter int //Types that satisfy the same interface func (w *WordsCounter) Write(p []byte) (int, error) { //separated string s := strings.NewReader(string(p)) bs := bufio.NewScanner(s) bs.Split(bufio.ScanWords) sum := 0 for bs.Scan() { sum++ } *w = WordsCounter(sum) return sum, nil }