随便记记(一)

一、for循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- 常规
for i := 0; i < count; i++ {}
- "while"
for condition { }
- "do-while"
for {
doSomething()
if condition { break }
}
- iterator loop
for k, v := range f.Value {}
- dead loop
for {}

二、Orthogonal Composition
1、vertical composition thought(垂直组合思维)
Go语言通过type embedding实现垂直组合。组合方式莫过于以下这么几种:

a) construct interface by embedding interface
通过在interface中嵌入interface type name,实现接口行为聚合,组成大接口。这种方式在stdlib中尤为常用。

1
2
3
4
type ReadWriter interface {
Reader
Writer
}

b) construct struct by embedding interface

1
2
3
4
type MyReader struct {
io.Reader // underlying reader
N int64 // max bytes remaining
}

c) construct struct by embedding struct

1
2
3
4
5
6
7
// sync/pool.go
type poolLocal struct {
private interface{} // Can be used only by the respective P.
shared []interface{} // Can be used by any P.
Mutex // Protects shared.
pad [128]byte // Prevents false sharing.
}

在struct中嵌入interface type name和在struct嵌入struct,都是“ 大专栏  随便记记(一)委派模式(delegate)”的一种应用。在struct中嵌入interface方便快速构建满足某一个interface的dummy struct,方便快速进行unit testing,仅需实现少数需要的接口方法即可,尤其是针对Big interface时。

struct中嵌入struct,被嵌入的struct的method会被提升到外面的类型中,比如上述的poolLocal struct,对于外部来说它拥有了Lock和Unlock方法,但是实际调用时,method调用实际被传给poolLocal中的Mutex实例。
2、small interface thought(小接口思维)
interface是Go语言真正的魔法。前面提到过,interface好比程序肌体的骨架关节,上下连接着骨架部件。interface决定了Go语言中类型的水平组合方式。interface与其实现者之间的关系是隐式的,无需显式的”implements”声明(但编译器会做静态检查);interface仅仅是method集合,而method和普通function一样声明,无需在特定位置。

3、horizontal composition thought(水平组合思维)
middleware这个词的含义可大可小,在Go Web编程中,常常指的是一个满足Handler interface的HandlerFunc类型实例。实质上:

1
middleware = wrapper function + adapter function type

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func (h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t := time.Now()
log.Printf("[%s] %q %vn", r.Method, r.URL.String(), t)
h.ServeHTTP(w, r)
})
}
func authHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := validateAuth(r.URL.Query().Get("auth"))
if err != nil {
http.Error(w, "bad auth param", http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
})
}
func main() {
http.ListenAndServe(":8080", logHandler(authHandler(http.HandlerFunc(index))))
}

原文地址:https://www.cnblogs.com/lijianming180/p/12286147.html