英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论