Effective Go -> Interface

來源:互聯網
上載者:User

標籤: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 第二個參數所需要的介面

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.