Documentation ¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Reader ¶
type Reader[T any] struct { // contains filtered or unexported fields }
Reader parses component data from CSV data.
This is thread compatible, i.e., it's safe for non-concurrent use and it can be combined with external synchronization so it can be called concurrently.
Example ¶
package main import ( "encoding/csv" "fmt" "io" "strings" "github.com/jabolopes/csvstruct" ) const testData = `Info.Name,Info.Class,Attributes.HP,Attributes.Damage,Player Alex,Fighter,100,10, Jayden,Wizard,90,20, Mary,Queen,,, Player,,,,0 ` type Info struct { Name string Class string } type Attributes struct { HP int Damage int } type Player struct{} type Prefab struct { Info *Info Attributes *Attributes Player *Player } func main() { reader := csvstruct.NewReader[Prefab](csv.NewReader(strings.NewReader(testData))) var prefab Prefab for { err := reader.Read(&prefab) if err == io.EOF { break } if err != nil { panic(err) } fmt.Printf("%#v\n", prefab.Info) fmt.Printf("%#v\n", prefab.Attributes) fmt.Printf("%#v\n", prefab.Player) } }
Output: &csvstruct_test.Info{Name:"Alex", Class:"Fighter"} &csvstruct_test.Attributes{HP:100, Damage:10} (*csvstruct_test.Player)(nil) &csvstruct_test.Info{Name:"Jayden", Class:"Wizard"} &csvstruct_test.Attributes{HP:90, Damage:20} (*csvstruct_test.Player)(nil) &csvstruct_test.Info{Name:"Mary", Class:"Queen"} (*csvstruct_test.Attributes)(nil) (*csvstruct_test.Player)(nil) &csvstruct_test.Info{Name:"Player", Class:""} (*csvstruct_test.Attributes)(nil) &csvstruct_test.Player{}
func NewReader ¶
NewReader returns a new reader using the given `reader` as the underlying CSV reader. The type `T` is the schema that is used to parse the data.
func (*Reader[T]) Clear ¶
func (r *Reader[T]) Clear()
Clears part of the internal state so that this is ready to continue parsing, namely, it clears the permanent error and all the internal descriptors. After Clear() is called, Read() will expect the next row to be a CSV header. This is useful if the same CSV file contains multiple tables of data.
func (*Reader[T]) Read ¶
Reads the next CSV row and returns typed data.
It's expected that the first row is the CSV header. This header is used to construct the column descriptors that will be used to direct column parsing.
If Clear() has been called, reading can resume and it's once again expected that the next row is a CSV header row.
Returns io.EOF when the end of file is reached. When an error is returned, the first return value is always nil. In other words, this either returns valid data or it returns an error, but never both simultaneously.