I'm trying to write a function that would open a file, build an object out of each line using another function it receives as parameter and return a slice of these objects, similar to this:
func readFile(filename string, transform func(string) interface {}) (list []interface {}) {
if rawBytes, err := ioutil.ReadFile(filename); err != nil {
log.Fatal(err)
} else {
lines := strings.Split(string(rawBytes), "
")
for i := range lines {
t := transform(lines[i])
list = append(list, t)
}
}
return list
}
I've tried to use it like this:
func transform(line string) (myObject *MyType) {
fields := strings.Split(line, "\t")
myObject.someField = fields[0]
myObject.anotherField = fields[1]
(...)
return myObject
}
And somewhere else I've called the original method like this:
readFile("path/to/file.txt", transform)
This gives me an error: cannot use transform (type func(string) *MyType) as type func(string) interface {} in function argument
Is there a different way to approach this problem in Go?
EDIT: Here's a similar but very simplified example of what I tried to do: http://play.golang.org/p/jLAsYojkII