-
Notifications
You must be signed in to change notification settings - Fork 86
/
interfaces.go
82 lines (70 loc) · 1.71 KB
/
interfaces.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"fmt"
"io"
"log"
"os"
)
// DatFile is a file in dat format
type DatFile struct{}
// Write persists the content
func (d *DatFile) Write(p []byte) (n int, err error) {
// open a dat file and write p
return
}
// PreffixOutput preffix content writed with some preffix
func PreffixOutput(w io.Writer, preffix []byte, content []byte) {
// receive a writer, then you can pass whatever that implements writer interface
// it's called polymorphism
content = append(preffix, content...)
w.Write(content)
}
// Barber cuts hair
type Barber interface {
CutHair() string
}
// Singer sings
type Singer interface {
Sing() string
}
// SingerBarber sings and cut hair
type SingerBarber interface {
Barber
Singer
}
//Person can sing and cut hair
type Person struct {
Name string
}
// Sing ...
func (p Person) Sing() string {
return "La la la!"
}
// CutHair ...
func (p Person) CutHair() string {
return "Almost cutted"
}
// CutHairAndSing cut hair while sing
func CutHairAndSing(sb SingerBarber) {
for i := 0; i < 3; i++ {
fmt.Println(sb.Sing())
fmt.Println(sb.CutHair())
}
}
func main() {
// standard output implements the method write, so can be used here
PreffixOutput(os.Stdout, []byte(">>> "), []byte("ls -a\n"))
// the same occurs with stdeer
PreffixOutput(os.Stderr, []byte(">>> "), []byte("ls -a\n"))
// you can use a file too
f, err := os.Create("/tmp/dat2")
if err != nil {
log.Fatal(err)
}
PreffixOutput(f, []byte(">>> "), []byte("ls -a\n"))
// or customized writers, it only have to implements writer interface
PreffixOutput(&DatFile{}, []byte(">>> "), []byte("ls -a\n"))
// person implements barber and singer interface then can be used as SingerBarber
p := Person{}
CutHairAndSing(p)
}