我正在尝试编写一个函数,该函数将打开一个文件,使用它作为参数接收的另一个函数从每一行构建一个对象,并返回这些对象的一部分,类似于:
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)
这给了我一个错误:不能在函数参数中使用transform (type func(string) *MyType) as type func(string) interface {}
Go 中有没有不同的方法来解决这个问题?
编辑:这是我尝试做的一个类似但非常简化的示例:http://play.golang.org/p/jLAsYojkII
最佳答案
只需将您的 transform
函数签名更改为 func transform(s string) interface{}
,但我认为这不是最好的解决方案。
关于go - 如何传递转换为接口(interface){}的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22076773/