標籤:style blog http color os strong
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 strcase 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
將依然存在,並且類型為字串,不過其為零值,一個Null 字元串
通過斷言描述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 intfunc (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 第二個參數所需要的介面