Add methods to anything
Go methods don’t have to be declared on structs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main
import "fmt"
type chanWriter chan string
func (w chanWriter) Write(b []byte) (int, error) {
w <- string(b)
return len(b), nil
}
func main() {
w := make(chanWriter)
go func() {
fmt.Fprintln(&w, "Hello, world!")
close(w)
}()
for s := range w {
print(s)
}
}
// Output: Hello, world!
In fact, methods can even be declared on functions. This can be useful when you want the simplest possible thing that fulfills an interface.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main
import (
"fmt"
"log"
"net/http"
)
type handler func(http.ResponseWriter, *http.Request)
func (f handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { f(w, r) }
func main() {
h := handler(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "Hello, world!")
})
http.Handle("/", h)
log.Fatal(http.ListenAndServe(":8080", nil))
}