I’ve run into a small issue for which I have a bit of an ugly solution only.
I cannot imagine I’m the first, but I haven’t found any clues on SO.
In the following (deliberately simplified) example I’d like to have a
receiver on the walk function which is my filepath.WalkFunc.
package main
import (
"fmt"
"os"
"path/filepath"
)
type myType bool
func main() {
var t myType = true
// would have loved to do something as:
// _ = filepath.Walk(".", t.walk)
// that does not work, use a closure instead
handler := func(path string, info os.FileInfo, err error) error {return t.walk(path, info, err)}
_ = filepath.Walk(".", handler)
}
func (t myType) walk(path string, info os.FileInfo, err error) error {
// do some heavy stuff on t and paths
fmt.Println(t, path)
return err
}
Func main() triggers walk() and because of the receiver t to walk(), I
cannot find another way than to use this ugly closure handler as an argument
to filepath.Walk(). I would have hoped for something more like
fileWalk(".", t.walk) but that does not work. It gives the compile error
” method t.walk is not an expression, must be called”
Is my closure solution the correct approach in this respect, or are there better options I don’t know of.
PS. This is one of several occasions in which I have to use this closure construction
to pass a handler function which has a receiver. So, this question is more related
to passing handler functions than to filepath behaviour.
Thanks for you suggestions.
This is not possible.
In Go, methods are mostly syntactic sugar, the receiver is actually the first parameter of the function. myType.walk basically has the signature
func(myType, string, os.FileInfo, error) error. You can see this when you try to pass myType.walk into filepath.Walk instead of t.walk.