如何传递将转换为interface{}的函数?

huangapple go评论139阅读模式
英文:

How to pass function that converts to interface{}

问题

我正在尝试编写一个函数,它会打开一个文件,并使用作为参数传递的另一个函数将每一行构建成一个对象,并返回这些对象的切片,类似于这样:

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
}

我尝试像这样使用它:

func transform(line string) (myObject *MyType) {
    fields := strings.Split(line, "\t")

    myObject.someField = fields[0]
    myObject.anotherField = fields[1]
    (...)
    return myObject
}

// 在其他地方调用原始方法:
readFile("path/to/file.txt", transform)

这给我一个错误:cannot use transform (type func(string) *MyType) as type func(string) interface {} in function argument

在Go语言中,有一个不同的方法来解决这个问题吗?

编辑:这里有一个类似但非常简化的示例,展示了我尝试做的事情:http://play.golang.org/p/jLAsYojkII

英文:

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

答案1

得分: 2

只需将您的transform函数签名更改为func transform(s string) interface{},但我不认为这是最佳解决方案。

英文:

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

huangapple
  • 本文由 发表于 2014年2月28日 02:07:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/22076773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定