IamNaN
IamNaN

Reputation: 6864

Finding functions that return a specific type

Perhaps this is a silly question, but is there a way to find all functions (in the standard library or GOPATH) that return a specific type?

For example there are many functions that take io.Writer as an argument. Now I want to know how to create an io.Writer and there are many ways to do so. But how can I find all the ways easily without guessing at packages and looking through all the methods to find those that return an io.Writer (or whatever other type I'm after)?

Edit: I should extend my question to also find types that implement a specific interface. Sticking with the io.Writer example (which admittedly was a bad example for the original question) it would be good to have a way to find any types that implement the Writer interface, since those types would be valid arguments for a function that takes takes an io.Writer and thus answer the original question when the type is an interface.

Upvotes: 3

Views: 302

Answers (2)

Uvelichitel
Uvelichitel

Reputation: 8490

In my days coding I'm personally rare in need to find functions returning Int16 and error(func can return few values in Go, you know)

For second part of your question there exists wonderful cmd implements written by Dominik Honnef go get honnef.co/go/implements After discover type that satisfy your conditions you can assume constructor for type (something like func NewTheType() TheType) would be just after TheType declaration in source code and docs. It's a proven Go practice.

Upvotes: 2

icza
icza

Reputation: 417622

Maybe not the best way but take a look at the search field at the top of the official golang.org website. If you search for "Writer":

http://golang.org/search?q=Writer

You get many results, grouped by categories like

Also note that io.Writer is an interface, and we all know how Go handles interfaces: when implementing an interface, there is no declaration of intent, a type implicitly implements an interface if the methods defined by the interface are declared. This means that you won't be able to find many examples where an io.Writer is created and returned because a type might be named entirely different and still be an io.Writer.

Things get a little easier if you look for a non-interface type for example bytes.Buffer.

Also in the documentation of the declaring package of the type the Index section groups functions and methods of the package by type so you will find functions and methods of the same package that return the type you're looking for right under its entry/link in the Index section.

Also note that you can check the dependencies of packages at godoc.org. For example you can see what packages import the io package which may be a good starting point to look for further examples (this would be exhausting in case of package io because it is so general that at the moment 23410 packages import it).

Upvotes: 3

Related Questions