Golang interfaces: Difference between revisions
From wikinotes
(Created page with "Similar to other languages, interfaces in go define a contract of method-signatures that implementors must have.<br> Unlike other languages, golang interfaces are implicit --...") |
(→Basics) |
||
Line 24: | Line 24: | ||
w.Write([]byte("Foobar")) | w.Write([]byte("Foobar")) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Libraries do not need to expose interfaces in go, you can create them for the subset of methods that are useful to you. | |||
</blockquote><!-- Basics --> | </blockquote><!-- Basics --> |
Revision as of 03:19, 6 June 2022
Similar to other languages, interfaces in go define a contract of method-signatures that implementors must have.
Unlike other languages, golang interfaces are implicit -- an object with all of the required methods automatically satisfies an interface.
Basics
// declare an interface type Writer interface { Write([]byte) (int, error) }// implement an interface (automatic if methods match) type PrinterWriter struct {} func (w PrinterWriter) Write(data []byte) (int, error) { // ... }var w Writer = PrinterWriter{} // <-- type 'Writer' w.Write([]byte("Foobar"))Libraries do not need to expose interfaces in go, you can create them for the subset of methods that are useful to you.