1. Interface implementation and type conversion
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 implements the sort interface to customize strings (custom printing can be performed throughStringMethod)
func (s Sequence) String() string { sort.Sort(s) return fmt.Sprint([]int(s))}
S and squence, [] int can be converted to each other
2. Interface Conversion 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 is a keyword (if you do not know the specific type)
3. assertion (know the specific type)
str := value.(string)
Conservative practice:
str, ok := value.(string)if ok { fmt.Printf("string value is: %q\n", str)} else { fmt.Printf("value is not a string\n")}
If type assertions failstrWill still exist, and the type is string, but it is null, an empty string
Use assertions to describe the switch:
if str, ok := value.(string); ok { return str} else if str, ok := value.(Stringer); ok { return str.String()}
4. Differences between structure and type calls
// 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 implements the interface required by the second HTTP. Handle parameter.