dousi6701 2012-10-26 12:28
浏览 169
已采纳

处理函数中的接收者,例如filepath.WalkFunc

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.

  • 写回答

2条回答 默认 最新

  • dongshou9343 2012-10-26 12:46
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题