-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_slices_test.go
62 lines (50 loc) · 1.43 KB
/
example_slices_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package csvdecoder_test
import (
"fmt"
"strings"
"github.com/stefantds/csvdecoder"
)
type MyStringCollection []string
// DecodeField implements the csvdecoder.Interface type
func (c *MyStringCollection) DecodeField(field string) error {
// the decode code is specific to the way the value is serialized.
// in this example the array is represented as int values separated by space
*c = MyStringCollection(strings.Split(field, " "))
return nil
}
func Example_slices() {
// the csv separator is a semicolon in this example
// the values are arrays serialized in two different ways.
exampleData := strings.NewReader(
`jon;elvis boris ahmed jane;["jo", "j"]
jane;lucas george;["j", "jay"]
`)
// create a new decoder that will read from the given file
decoder, err := csvdecoder.NewWithConfig(exampleData, csvdecoder.Config{Comma: ';'})
if err != nil {
// handle error
return
}
type Person struct {
Name string
Friends MyStringCollection
Nicknames []string
}
// iterate over the rows in the file
for decoder.Next() {
var p Person
// scan the first values to the types
if err := decoder.Scan(&p.Name, &p.Friends, &p.Nicknames); err != nil {
// handle error
return
}
fmt.Printf("%v\n", p)
}
// check if the loop stopped prematurely because of an error
if err = decoder.Err(); err != nil {
// handle error
return
}
// Output: {jon [elvis boris ahmed jane] [jo j]}
// {jane [lucas george] [j jay]}
}