Documentation
¶
Overview ¶
Package csvstruct allows decoding of string slice obtained from a csv.Reader.Read call into a struct type.
It supports decoding to string, integer, and float struct fields.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Decoder ¶
Decoder is a function that decodes CSV row to dst, which must be a pointer to a struct type. Decoder must be called on the same type it was created from by the NewDecoder call.
Example ¶
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"strings"
)
type Person struct {
FirstName string `csv:"first_name"`
LastName string `csv:"last_name"`
}
const Table = `first_name,last_name,username
"Rob","Pike",rob
Ken,Thompson,ken
"Robert","Griesemer","gri"
`
func main() {
r := csv.NewReader(strings.NewReader(Table))
header, err := r.Read()
if err != nil {
log.Fatal(err)
}
dec, err := NewDecoder(header, Person{})
if err != nil {
log.Fatal(err)
}
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
var person Person
if err := dec(record, &person); err != nil {
log.Fatal(err)
}
fmt.Println(person.FirstName, person.LastName)
}
}
Output: Rob Pike Ken Thompson Robert Griesemer
func NewDecoder ¶
NewDecoder takes CSV header and dst which must be a struct type or a pointer to a struct type with struct "csv" tags mapped to header names, and returns a Decoder function for this type and field ordering. It does not modify dst.
Only exported fields are processed.
Click to show internal directories.
Click to hide internal directories.