Skip to content

Commit

Permalink
add array and struct types
Browse files Browse the repository at this point in the history
  • Loading branch information
name5566 committed Jan 22, 2015
1 parent d18ca39 commit 9f085d7
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 10 deletions.
15 changes: 15 additions & 0 deletions recordfile/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ func Example() {
// index 1
IndexStr string "index"
Str string
Arr1 [2]int
Arr2 [3][2]int
Arr3 []int
St struct {
Name string "name"
Num int "num"
}
}

rf, err := recordfile.New(Record{})
Expand All @@ -38,6 +45,10 @@ func Example() {

r = rf.Indexes(1)["three"].(*Record)
fmt.Println(r.Str)
fmt.Println(r.Arr1[1])
fmt.Println(r.Arr2[2][0])
fmt.Println(r.Arr3[0])
fmt.Println(r.St.Name)

// Output:
// 1
Expand All @@ -46,4 +57,8 @@ func Example() {
// cat
// cat
// book
// 6
// 4
// 6
// name5566
}
24 changes: 18 additions & 6 deletions recordfile/recordfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package recordfile

import (
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"os"
Expand Down Expand Up @@ -46,18 +47,25 @@ func New(st interface{}) (*RecordFile, error) {
case reflect.Float32:
case reflect.Float64:
case reflect.String:
case reflect.Struct:
case reflect.Array:
case reflect.Slice:
default:
return nil, errors.New(fmt.Sprintf("invalid type: %v %v",
f.Name, kind.String()))
}

tag := f.Tag
switch tag {
case "":
case "index":
default:
return nil, errors.New(fmt.Sprintf("invalid tag: %v %v",
f.Name, string(tag)))
if tag == "index" {
switch kind {
case reflect.Struct:
fallthrough
case reflect.Array:
fallthrough
case reflect.Slice:
return nil, errors.New(fmt.Sprintf("invalid tag: %v %v",
f.Name, tag))
}
}
}

Expand Down Expand Up @@ -162,6 +170,10 @@ func (rf *RecordFile) Read(name string) error {
}
} else if kind == reflect.String {
field.SetString(strField)
} else if kind == reflect.Struct ||
kind == reflect.Array ||
kind == reflect.Slice {
err = json.Unmarshal([]byte(strField), field.Addr().Interface())
}

if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions recordfile/test.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
�������� �������� �ַ������� �ַ�������
1 0 one knife
2 0 two cat
3 0 three book
�������� �������� �ַ������� �ַ������� �������� Ƕ������ �䳤���� �ṹ������
1 0 one knife "[1, 2]" "[[0,1], [1,2], [2,3]]" "[1, 2, 3]" "{""name"": ""name5566"", ""num"": 1}"
2 0 two cat "[3, 4]" "[[1,2], [2,3], [3,4]]" "[4, 5]" "{""name"": ""name5566"", ""num"": 2}"
3 0 three book "[5, 6]" "[[2,3], [3,4], [4,5]]" [6] "{""name"": ""name5566"", ""num"": 3}"

0 comments on commit 9f085d7

Please sign in to comment.