github.com/huandu/go@v0.0.0-20151114150818-04e615e41150/doc/progs/eff_sequence.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "fmt" 9 "sort" 10 ) 11 12 func main() { 13 seq := Sequence{6, 2, -1, 44, 16} 14 sort.Sort(seq) 15 fmt.Println(seq) 16 } 17 18 type Sequence []int 19 20 // Methods required by sort.Interface. 21 func (s Sequence) Len() int { 22 return len(s) 23 } 24 func (s Sequence) Less(i, j int) bool { 25 return s[i] < s[j] 26 } 27 func (s Sequence) Swap(i, j int) { 28 s[i], s[j] = s[j], s[i] 29 } 30 31 // Method for printing - sorts the elements before printing. 32 func (s Sequence) String() string { 33 sort.Sort(s) 34 str := "[" 35 for i, elem := range s { 36 if i > 0 { 37 str += " " 38 } 39 str += fmt.Sprint(elem) 40 } 41 return str + "]" 42 }