dtby67541 2014-02-27 18:07
浏览 50
已采纳

如何传递转换为接口的函数{}

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

  • 写回答

1条回答 默认 最新

  • douyulv6921 2014-02-27 19:03
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大