Effective Go -> Interface

1.接口实现及类型转换
 1 type Sequence []int
 2 
 3 // Methods required by sort.Interface.
 4 func (s Sequence) Len() int {
 5     return len(s)
 6 }
 7 func (s Sequence) Less(i, j int) bool {
 8     return s[i] < s[j]
 9 }
10 func (s Sequence) Swap(i, j int) {
11     s[i], s[j] = s[j], s[i]
12 }
13 
14 // Method for printing - sorts the elements before printing.
15 func (s Sequence) String() string {
16     sort.Sort(s)
17     str := "["
18     for i, elem := range s {
19         if i > 0 {
20             str += " "
21         }
22         str += fmt.Sprint(elem)
23     }
24     return str + "]"
25 }

Squence 实现了sort接口,可以自定义字符串(自定义的打印可以通过String方法来实现)

func (s Sequence) String() string {
    sort.Sort(s)
    return fmt.Sprint([]int(s))
}

s 与 Squence ,[]int可相互转换

 

2.接口转换 switch
type Stringer interface {
    String() string
}

var value interface{} // Value provided by caller.
switch str := value.(type) {
case string:
    return str
case Stringer:
    return str.String()
}

type为关键字(在不知道具体类型)

 

3.断言(知道具体类型)

str := value.(string)

保守做法:

str, ok := value.(string)
if ok {
    fmt.Printf("string value is: %q\n", str)
} else {
    fmt.Printf("value is not a string\n")
}

如果类型断言失败,则str将依然存在,并且类型为字符串,不过其为零值,一个空字符串

 

通过断言描述switch:

if str, ok := value.(string); ok {
    return str
} else if str, ok := value.(Stringer); ok {
    return str.String()
}

 

 4.结构与类型调用区别
// Simple counter server.
type Counter struct {
    n int
}

func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    ctr.n++
    fmt.Fprintf(w, "counter = %d\n", ctr.n)
}

 

// Simpler counter server.
type Counter int

func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    *ctr++
    fmt.Fprintf(w, "counter = %d\n", *ctr)
}


5.type xx func...

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers.  If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler object that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(c, req).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, req *Request) {
    f(w, req)
}
// Argument server.
func ArgServer(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintln(w, os.Args)
}
http.Handle("/args", http.HandlerFunc(ArgServer))

HandlerFunc会实现 http.Handle 第二个参数所需要的接口

posted @ 2014-07-23 16:13  梦想's技术人员  阅读(195)  评论(0编辑  收藏  举报