肥皂起泡泡
Go 的sort包附带了一个很好的例子。请参阅修改后的实现,该实现应该可以满足您的要求。package mainimport ( "encoding/csv" "fmt" "io" "log" "sort" "strings")// Unsorted sample datavar unsorted = `Balaam,Wileen,Saint LouisMeachan,Lothaire,LefengzhenScoggin,Ivonne,PagHawarden,Audrye,LeiriaClaypool,Biddy,MaiorcaStanford,Douglas,BáguanosPetriello,Yvor,ObryteHatter,Margette,LuopingPepall,Linzy,HucunCarter,Kit,Parungjawa`type Person struct { Lastname string Firstname string City string}// Create a new Person record from a given string slicefunc NewPerson(fields []string) (p Person, err error) { if len(fields) < 3 { return p, fmt.Errorf("not enough data for Person") } p.Lastname = fields[0] p.Firstname = fields[1] p.City = fields[2] return}// ByLastname implements sort.Interface for []Person based on the Lastname field.type ByLastname []Personfunc (a ByLastname) Len() int { return len(a) }func (a ByLastname) Swap(i, j int) { a[i], a[j] = a[j], a[i] }func (a ByLastname) Less(i, j int) bool { return a[i].Lastname < a[j].Lastname }func main() { // Open unsorted CSV from string r := csv.NewReader(strings.NewReader(unsorted)) var people []Person for { // Read CSV line by line record, err := r.Read() if err == io.EOF { break } if err != nil { log.Fatal(err) } // Create Person from line in CSV person, err := NewPerson(record) if err != nil { continue } people = append(people, person) } // Sort CSV by Lastname sort.Sort(ByLastname(people)) // Print to stdout for _, p := range people { fmt.Printf("%s %s from %s\n", p.Lastname, p.Firstname, p.City) } // Here you would write your CSV}