Golang interfaces: Difference between revisions

From wikinotes
No edit summary
Line 30: Line 30:
Libraries do not need to expose interfaces in go, you can create them for the subset of methods that are useful to you.
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 -->
== Primitive Interfaces ==
<blockquote>
{{ TODO |
test this code! }}
Interfaces can also be created on primitives.
<syntaxhighlight lang="go">
type Doubler interface {
    Double() int
}
func (value *int) {
    *value = *value * 2
}
num := 10
var doubler Doubler = &num
num.Double() // 20
</syntaxhighlight>
</blockquote><!-- Primitive Interfaces -->

Revision as of 03:28, 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

In go, many interfaces expose just a single method, and are named after the method they expose.
Frequently, interfaces are implemented on structs (but they can be for any type).

// 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.

Primitive Interfaces

TODO:

test this code!

Interfaces can also be created on primitives.

type Doubler interface {
    Double() int
}

func (value *int) {
    *value = *value * 2
}

num := 10
var doubler Doubler = &num
num.Double() // 20