Trying to understand Go interfaces as a newcomer
Hi Gophers !
I'm trying to learn Go on my spare time coming from Java / Node.js background and there is something I don't really understand about interfaces.
Let's say that I have an http.ResponseWriter :
type ResponseWriter interface {
[...]
Write([]byte) (int, error)
[...]
}
And now let's consider the io.Writer interface :
type Writer interface {
Write(p []byte) (n int, err error)
}
Put it this way, it's kind of obvious, http.ResponseWriter implements io.Writer, thus I can use something like this :
func Handler(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "blabla.\n")
}
As a new Gopher, this is kind of ... odd in my opinion, since the interface implementation is not explicit in Go, it seems to me that you must know them by heart.
What if I didn't made the effort to read the Writer and ResponseWriter interface ? It's not really obvious that ResponseWriter implements Writer (besides the name).
It seems to me that it may become hard to understand which interface implements which in some complex scenarios
Why can't we write something like this ?
type ResponseWriter interface {
[...]
io.Writer
[...]
}
This way, it becomes obvious that ResponseWriter is an io.Writer, and thus I can easily know that I can use all the function that takes an io.Writer interface as an argument.
I don't want to be disrepectful to the langage, and perhaps I'm just wrong, but I believe that the implicit implementation may cause trouble to understand code. For example, as a new Gopher it's sometimes hard to understand that I can use a function because my type implements its methods.
Not to say that Java is perfect, but it seems to me that having explicit interface implementation makes the code easier to understand.
Thank you, and please let me know if I made an English mistake !
Posted Sep 22, 2020, 9:59 PM UTC
You can! That's valid. It's also totally equivalent to the existing definition. I'm not entirely sure why it's not expressed that way.
—
An important and fundamental thing about Go interfaces is that they're meant to be defined and used by the code that consumes them, as a way to express the behavior that they need from a dependency. This is different than many (most?) other languages, where things like interfaces are typically defined and used by the code that implements them, as a way to express the behavior that they're providing to consumers. This "decoupling" enables a lot of the flexibility and power of the language.