2

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), "\n")
        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

3
  • Well, you can change transform signature to func transform(s string) interface{}, but I don't think it's correct and acceptable answer. Commented Feb 27, 2014 at 18:21
  • @Kavu It might work. If what you're suggesting is this: play.golang.org/p/V2nDekb6f5 it seems to work Commented Feb 27, 2014 at 18:26
  • @Kavu I can confirm it works. I just needed to get the output of readFile and transform it into a slice of MyType values. It's enough for me, if you want to post it as an answer, I'll be glad to accept it! Commented Feb 27, 2014 at 18:44

1 Answer 1

2

Just change your transform function signature to func transform(s string) interface{}, but I don't think it is the best solution.

Sign up to request clarification or add additional context in comments.

1 Comment

You can combine this with a type switch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.