Get names of structs that implement an interface or inherit a struct - go

Is it possible to get a slice of strings that represent the names of all types that implement an interface or inherit from a specific struct in a specific package using reflection?

After some research on the reflect package's doc, I don't think it's possible. That's not the way reflection work in go: the interfaces mechanism not beeing declarative (but duck-typed instead), there is no such list of types.
That said, you may have more luck using the ast package to parse your project, get the list of types, and check wheter or not they implement an interface, then write some code to give you the said slice. That would add a step to compilation, but could work like a charm.

AFAIK, you can't do this with reflect, since packages are kinda out of reflect's scope.
You can do this the same way godoc's static analysis works. That is, using code.google.com/p/go.tools/go/types to parse the package's source code and get the type info.

The go oracle can do this. https://godoc.org/code.google.com/p/go.tools/oracle
Here is the relevant section of the user manual.

Related

Is it possible to discover all types and functions in a package using reflection?

Is it possible to get all the types and functions defined in a package using reflection at runtime? To make the question clear, in C# we can do this by using a method called ExportedTypes on an assembly and it returns a list of classes.
To be particular, what I need to do is to obtain a list of methods that have a particular return type while being able to invoke them dynamically when required.
Edit: I already know about the AST package, but I am asking in particular about the reflection package.

How can I enforce correct construction whilst respecting the golang CodeReviewComments rule on interfaces?

The Interfaces rule in the official Go Code Review Comments document says that packages should return concrete types rather than interfaces. The motivation for this is so that:
...new methods can be added to implementations without requiring extensive refactoring.
which I accept could be a good thing.
But what if a type I'm writing has a dependency without which it cannot serve its purpose? If I export the concrete type, developers will be able to instantiate instances without that dependency. To code defensively for the missing dependency, I then have to check for it in every method implementation and return errors if it is absent. If the developer missed any hints not to do this in my documentation, she or he won't learn about the problem until run time.
On the other hand, if I declare and return an interface with the methods the client needs, I can unexport the concrete type and enforce the use of a factory method which accepts the dependency as an argument and returns the interface plus an error. This seems like a better way to ensure correct use of the package.
Am I somehow not properly getting into the go spirit by thinking like this? Is the ethic of the language that it's okay to have a less-than-perfect encapsulation to give more flexibility to developers?
You may expect developers to read the doc you provide, and you may rely on them following the rules you set. Yes, lazy developers will bump their head from time to time, but the process of developing isn't without having to learn. Everything cannot be made explicit or enforced, and that's all right.
If you have an exported struct type Example and you provide a constructor function NewExample(), that's a clear indication that NewExample() should be used to construct values of Example. Anyone attempting to construct Example manually is expected to know what fields must be set for it to be "operational". The aim is always to make the zero value fully functional, but if that can't be achieved, the constructor function is the idiomatic way to go.
This isn't uncommon, there are countless examples in the standard library, e.g. http.Request, json.Encoder, json.Decoder, io.SectionReader, template.Template.
What you must ensure is that if your package returns values of your structs, they must (should) be properly initialized. And also if others are expected to pass values of your structs created by them, you must provide an easy way for them to create valid values of your structs (constructor function). Whether the custom struct values other developers create themselves are "valid", that shouldn't be of your concern.

Struct Properties vs Generics in Racket

Racket seems to have two mechanisms for adding per-type information to structs: generics and properties. Unfortunately, the documentation doesn't seem to indicate when one is preferred over the other. The docs do say:
Generic Interfaces provide a high-level API on top of structure type properties.
But that doesn't seem to provide a good intuition when I should use one over the other. It does seem pretty clear that define-generic provides a much higher level interface than make-struct-type-property. But many struct types still only use properties, which seems to indicate that there are still cases where the low-level API is preferred.
So the question is, when is using the struct properties system better than using the generics one, or does the properties library only exist as a historic relic?
The struct property system is the implementation strategy for the generic interface library, so it's not deprecated. It, or something like it, is necessary to make generic interfaces work. Not all uses of struct properties make sense as generic interfaces either.
That said, for many typical use cases the define-generic form is preferred. As the #:methods form for structs suggests, it is useful for code that is organized in an object-oriented fashion with interface-based dispatch. Examples of this include sequences (gen:sequence from data/collection) and dictionaries (gen:dict).
Plain struct properties in the Racket codebase are typically used when some data just needs to be stored in a struct as metadata, or when there is only one "method" and it's needlessly complicated to use define-generic, or when the interface is more complicated than "just put a procedure in here". Examples include prop:procedure or prop:evt.

Detect if golang method is internal?

I'm writing a function that iterates over the methods on a given struct and binds the methods to handlers. I would like to skip over internal methods if possible. I'm not sure if this is possible to do so explicitly - I reviewed the documentation for the reflect package and I didn't see a means to detect if a given Value is an internal method. I know I can get the method's name, and then check if it starts with a lowercase character but I'm not sure if there's a kosher way to accomplish this. It's also possible that the internal / public boundary really only exists at compile time anyways, so there really isn't even a way of knowing this beyond the method's name. In either case I'd like to know for sure. Thanks!
The reflect package will not give you unexported methods via Type.Method. Pretty much, if you can see it via reflect, it is already exported.
See https://play.golang.org/p/61qQYO38P0

How to import package by path from string in Go?

I have a string with name of package (like "my/package/test") and I wanna import that and call some function from package.
Something like this:
func init() {
var pkg string = "test/my/pkg"
import pkg
pkg.Test()
}
PS. Thanks for help
The Go language does not allow what you mentioned in your example. This is a conscious choice. In my opinion, the reason behind this choice has to do with compiler performance and ease of code understanding by the machine. This for example enables tools such as gofix that can partially fix Go code without need for user intervention.
It also enables a programmer to clearly see all of the statically imported packages used by the program.
See also the grammar rules for source file organization in the Go language specification.
In relation to dynamically loading packages at run-time: Go has no support for loading packages at run-time. A future Go run-time might implement this feature (for example, it is occasionally being requested in messages in the golang-nuts mailing list), but the current state is that there is no support for this feature.
That's not possible in Go. The linker has to know the dependencies at compile-time, your string (and the init-function) are however evaluated at run-time. Also note, that parts of your programs which are not used, i.e. everything which isn't referred explicitly, wont even be part of the final binary - so reflection is not possible either.
If you need something like that, you have to manage the mapping on your own. You can for example use a global map in one package and use the init functions in the other packages to register the relevant functions, by adding them to the map. After that, you can use the map to do your look-ups dynamically.
Take a look at the http package for example. In a fictional blog package you might use the blog.init() function to register a couple of http handlers using the http.HandleFunc(pattern, handler) function. The main package then might call http.ListenAndServe() which looks up the right handlers at run-time.

Resources