-
Notifications
You must be signed in to change notification settings - Fork 140
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3649 from onflow/bastian/document-go-patterns
- Loading branch information
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|