I'm designing an simple application using go to read a few file formats representing customers file formats. My first idea is to read each file line and then parse it to an struct. So far so good, but i need to split each field based on it's index. For example:
line := "1003450020170804890000000022344"
Id starts on position 1 to position 4 = 1003 CustomerId is position 5 to 7 and all other fields related to that structure.
I would like to know if there's something more efficient to read a format and apply to this file line, i thought to create some struct for each field and have the start and end fields, but it sounds weird to me.
type Record struct {
Id int
Date time.Time
Value float64
ClientId int32
}
type RecordId struct {
Start int
Finish int
Value int
}
type ClientId struct {
Start int
Finish int
Value int32
}
I don't know if i'm on the way, maybe there's something more elegant that will work better on this case.
var a, b int
n, err := fmt.Sscanf("1003450020170804890000000022344", "%4d%3d", &a, &b)
if err != nil {
// ...
}
fmt.Println(a) // 1003
fmt.Println(b) // 450
Then you could create a structure with these.
A parse function is simple and probably sufficient, rather than declaring ancillary data structures.
Eg, something along the lines of:
func NewRecord(line string) (*Record, error) {
if len(line) < 14 {
return nil, fmt.Errorf("line is too short: %d", len(line))
}
return &Record{
Id: line[0:4],
Name: line[4:14],
}, nil
}