Пакет
Go sort
поставляется с отличным примером . Смотрите исправленную реализацию, которая должна делать то, о чем вы спрашиваете.
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"sort"
"strings"
)
// Unsorted sample data
var unsorted = `Balaam,Wileen,Saint Louis
Meachan,Lothaire,Lefengzhen
Scoggin,Ivonne,Pag
Hawarden,Audrye,Leiria
Claypool,Biddy,Maiorca
Stanford,Douglas,Báguanos
Petriello,Yvor,Obryte
Hatter,Margette,Luoping
Pepall,Linzy,Hucun
Carter,Kit,Parungjawa
`
type Person struct {
Lastname string
Firstname string
City string
}
// Create a new Person record from a given string slice
func 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 []Person
func (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
}