title: How am I meant to use Filepath.Walk in Go?
body: <p>The <code>filepath.Walk</code> function takes a function callback. This is straight function with no context pointer. Surely a major use case for <code>Walk</code> is to walk a directory and take some action based on it, with reference to a wider context (e.g. entering each file into a table).</p>
  
  <p>If I were writing this in C# I would use an object (with fields that could point back to the objects in the context) as a callback (with a given callback method) on it so the object can encapsulate the context that <code>Walk</code> is called from.</p>
  
  <p>(EDIT: user "<a href="https://stackoverflow.com/users/122718/usr">usr</a>" suggests that the closure method occurs in C# too)</p>
  
  <p>If I were writing this in C I'd ask for a function and a context pointer as a <code>void *</code> so the function has a context pointer that it can pass into the <code>Walk</code> function and get that passed through to the callback function.</p>
  
  <p>But Go only has the function argument and no obvious context pointer argument.</p>
  
  <p>(If I'd designed this function I would have taken an object as a callback rather than a function, conforming to the interface <code>FileWalkerCallback</code> or whatever, and put a <code>callback(...)</code> method on that interface. The consumer could then attach whatever context to the object before passing it to <code>Walk</code>.)</p>
  
  <p>The only way I can think of doing it is by capturing the closure of the outer function in the callback function. Here is how I am using it:</p>
  
  <pre><code>func ScanAllFiles(location string, myStorageThing *StorageThing) (err error) {
      numScanned = 0
  
      // Wrap this up in this function's closure to capture the `corpus` binding.
      var scan = func(path string, fileInfo os.FileInfo, inpErr error) (err error) {
          numScanned ++
  
          myStorageThing.DoSomething(path)
      }
  
      fmt.Println("Scan All")
  
      err = filepath.Walk(location, scan)
  
      fmt.Println("Total scanned", numScanned)
  
      return
  }
  </code></pre>
  
  <p>In this example I create the callback function so its closure contains the variables <code>numScanned</code> and <code>myStorageThing</code>.</p>
  
  <p>This feels wrong to me. Am I right to think it feels weird, or am I just getting used to writing Go? How is it intended for the <code>filepath.Walk</code> method to be used in such a way that the callback has a reference to a wider context?</p>