1.接口实现及类型转换
type Sequence []int // Methods required by sort.Interface.
func (s Sequence) Len() int {
return len(s)
}
func (s Sequence) Less(i, j int) bool {
return s[i] < s[j]
}
func (s Sequence) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
} // Method for printing - sorts the elements before printing.
func (s Sequence) String() string {
sort.Sort(s)
str := "["
for i, elem := range s {
if i > {
str += " "
}
str += fmt.Sprint(elem)
}
return str + "]"
}
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 第二个参数所需要的接口