Hacker News new | ask | show | jobs
by ridiculous_fish 3845 days ago
When navigating unfamiliar Go codebases, it's hard to know which types fulfill an interface. Say you have a function that takes an Animal; how do you figure out what to call it with?

Or to give a concrete example, say you want to do formatted output to stderr. How is one supposed to determine that os.Stderr is something that can be passed to fmt.Fprintf? Is there a better way than manually comparing method signatures?

2 comments

A pattern that helps with this (tangentially) is to explicitly declare methods to implement an interface at type declaration time:

    type File struct {
        ...
    }
    
    var _ io.Writer = (*File)(nil)
It's not a panacea, but it helps. If you write all your own code this way, at least it will be easy to see which interfaces your own types implement, and (with a grep or GoRef) vice versa.

Plus you get interface implementation checking, so your error messages actually make sense if the interface or type method signatures unexpectedly change.

Again, this is not a real solution to your problem, but it has enough advantages to be worth mentioning.

Use the Go oracle with an "implements" query.
Hey, that's pretty cool. I was able to get it to work, though it is very awkward to use directly (it's designed to be integrated into text editors).
Yes, I use it via vim-go.

You can also use it from a local godoc instance: https://golang.org/lib/godoc/analysis/help.html

And there's Pythia: https://github.com/fzipp/pythia

So beside familiarizing the language syntax, I need to be aware of a set of unofficial tools and plugins, which are likely going to change in the next couple months, to be able to read the code.
It's an official tool. Also, most interfaces are very small (one to two methods) so it's pretty easy to figure out. I read/write a decent amount of Go every day and it's not often that I'm asking myself "what implements this interface?".
"go oracle" is right there with "go build" etc, an official tool that shouldn't change any more than the other tools that's part of the Go distribution.