Effective Go-4
Interfaces and other types Interface Sequence这个例子,调用sort package中的方法,对于集合要实现sort的接口:Len(), Less(i,j int) bool 和 Swap(i,j int)。Sequence同时通过String()对集合内容进行格式化。 package sequence_test import ( "fmt" "sort" "testing" ) type Sequence []int 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] } func (s Sequence) Copy() Sequence { copy := make(Sequence, 0, len(s)) return append(copy, s...) } func (s Sequence) String() string { s = s.Copy() sort.Sort(s) str := "[" for i, elem := range s { if i > 0 { str += " " } str += fmt.Sprint(elem) } return str + "]" } func (s Sequence) Stringsprint() string { s = s.Copy() sort.Sort(s) return fmt.Sprint(s) } func (s Sequence) StringIntSlice() string { s = s.Copy() sort.IntSlice(s).Sort() return fmt.Sprint(s) } func TestSequence(t *testing.T) { var s Sequence = Sequence{100, 12, 83, 34, 59, 86} t.Logf("%#v", s) t.Log(s) t.Log(s.String()) t.Log(s.Stringsprint()) t.Log(s.StringIntSlice()) } === RUN TestSequence f:\GO\go_test\sequence\sequence_test.go:54: sequence_test.Sequence{100, 12, 83, 34, 59, 86} f:\GO\go_test\sequence\sequence_test.go:55: [12 34 59 83 86 100] f:\GO\go_test\sequence\sequence_test.go:56: [12 34 59 83 86 100] f:\GO\go_test\sequence\sequence_test.go:57: [12 34 59 83 86 100] f:\GO\go_test\sequence\sequence_test.go:58: [12 34 59 83 86 100] --- PASS: TestSequence (0.00s) PASS ok loop/sequence 1.996s 类型转换 String()接口通过 “for i, elem := range”方式实现,也可以像Stringsprint直接调用fmt.Sprint处理实现。 ...