Last active
February 4, 2019 10:00
-
-
Save urakozz/5a567025e2f52ea1449ed50771345290 to your computer and use it in GitHub Desktop.
Golang snippets
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
package main | |
import "io" | |
func main() { | |
} | |
// Storager - interface, naming recommendation is to have 'er' ending | |
type Storager interface { | |
DoSave(v []byte) error | |
} | |
// NewStorage - constructor for the struct. Return type is interface so it's also a compile time check that your struct fits to the interface | |
func NewStorage(opts: StorageOpts) Storager { | |
return &storage{opts: opts} | |
} | |
// StorageOpts - struct with options for the constructor | |
type StorageOpts struct { | |
address string | |
} | |
// storage - it's our class actually. In this case it's private | |
type storage struct { | |
opts StorageOpts | |
} | |
// DoSave - fit 'storage' to the Storager interface | |
func (s *storage) DoSave(v []byte) error { | |
// bla bla | |
return nil | |
} | |
// Close - fit 'storage' to the io.Closer interface | |
func (s *storage) Close() { | |
} | |
// this construction ensures on compile-time that your struct implements some interface | |
var _ Storager = (*storage)(nil) | |
var _ io.Closer = (*storage)(nil) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment