Hacker News new | ask | show | jobs
by Goopplesoft 4210 days ago
Go's interfaces are great, but one of my annoyances is that you can't define an interface with values (methods only). Which makes little sense considering it works just fine with getters and setters. i.e:

    type Blah interface { Var string }
wont work, but

    type Blah interface { GetVar() string } 
does. I'm sure theres a reason for this. Can someone shed some light?
2 comments

The purpose of the interface is to abstract how something is done.

In your example, GetVar() can be implemented in a number of ways. Returning Var field of Blah struct is only one such way (and if there was only one implementation, there would be no need for an interface).

In that light, adding variables as part of interface doesn't make sense. Variables are fixing the thing that interface is meant to make flexible.

In Go, you can achieve re-using of a bunch of variables (and their methods) by embedding - put the variables you want to re-use into a separate struct and embed that struct in other structs. See https://golang.org/doc/effective_go.html#embedding

It seemed to me that interfaces have a second function of providing partial uniformity across types (not just abstracting procedures). I.e the Animal interface has a method `Speak() string` and you have a function that takes an Animal that prints something like "Animal type {species} says {speak}" you would have to define a getter on the Animal's species even though its not a really a procedure. But I see what you mean though. Thanks!
If you have a function that requires both the species and a speak message from an animal, it would make sense for the interface to have a function that returns both the species and speak strings. I think that this [0] does what you would want.

If you want to guarantee that two structs contain a set of the same required fields, I believe the best practice would be to include an anonymous field for a struct with the fields across both. [1]

[0] http://play.golang.org/p/0zMqPUicgq [1] http://play.golang.org/p/cM3XPfitxH

That second one is damn interesting, didn't know you could do that. Thanks!
An interface takes any value for which the required methods are defined on it.

Methods can be defined on any type declared in the package.

A type in go can be a lot more that just a struct; it can be any type in the language. So while it may make sense to have values on interfaces for structs, values don't make any sense for functions, pointers, interfaces, or extensions to built in types.