Skip to content

Commit

Permalink
document Go patterns used in the codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
turbolent committed Oct 28, 2024
1 parent 0b92557 commit a0ef085
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions docs/go.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Go

## Patterns

- To ensure interface cannot be implemented in other packages,
add a private function (first character must be lower-case) named "is" + type name,
which takes no arguments, returns nothing, and has an empty body.

For example:

```go
type I interface {
isI()
}
```

See https://go.dev/doc/faq#guarantee_satisfies_interface

- To ensure a type implements an interface at compile-time,
use the "interface guard" pattern:
Introduce a global variable named `_`, type it as the interface,
and assign an empty value of the concrete type to it.

For example:

```go
type T struct {
//...
}
var _ io.ReadWriter = (*T)(nil)
func (t *T) Read(p []byte) (n int, err error) {
// ...
```

See
- https://go.dev/doc/faq#guarantee_satisfies_interface
- https://rednafi.com/go/interface_guards/
- https://github.com/uber-go/guide/blob/master/style.md#verify-interface-compliance
- https://medium.com/@matryer/golang-tip-compile-time-checks-to-ensure-your-type-satisfies-an-interface-c167afed3aae

0 comments on commit a0ef085

Please sign in to comment.