Documentation
¶
Overview ¶
Package interfaces demonstrates idiomatic Go interface implementation patterns
Package interfaces demonstrates idiomatic Go interface implementation patterns.
Package interfaces demonstrates idiomatic Go interface implementation patterns ¶
Package interfaces demonstrates idiomatic Go interface implementation patterns ¶
Package interfaces demonstrates idiomatic Go interface implementation patterns ¶
Package interfaces demonstrates idiomatic Go interface implementation patterns ¶
Package interfaces demonstrates idiomatic Go interface implementation patterns ¶
Package interfaces demonstrates idiomatic Go interface implementation patterns.
Package interfaces demonstrates idiomatic Go interface implementation patterns ¶
Package interfaces demonstrates idiomatic Go interface implementation patterns
Index ¶
- func AcceptReturnDemo()
- func AdvancedOperation(rws FileReadWriteSeeker) error
- func BadFactory() io.Reader
- func BadFunction(data any) any
- func BasicInterfaceDemo()
- func BetterFunction(data string) int
- func CalculatorDemo()
- func Collection()
- func CompositionDemo()
- func ConfigExample()
- func CopyData(r FileReader, w FileWriter) (int, error)
- func CustomSortExample()
- func DemonstrateAntiPatterns()
- func DemonstrateStdlibInterfaces()
- func DisplayProperties(item DisplayItem)
- func DuckTypingBasics()
- func DuckTypingDemo()
- func EmptyInterfaceDemo()
- func ExtendingInterfacesDemo()
- func HttpHandlerExample()
- func IOCompositionExample()
- func InconsistentUsage()
- func InterfaceEmbeddingDemo()
- func InterfaceTestingDemo()
- func InterfaceUpgradeDemo()
- func JSONInterfaceExample()
- func LoggingMiddleware(next http.Handler) http.Handler
- func MethodSetExample()
- func MultiLevelCompositionDemo()
- func MultipleInterfacesDemo()
- func NilInterfaceDemo()
- func ParseValue(s string) (any, error)
- func PointerReceiverDemo()
- func PrintItems(items []Stringable)
- func PrintReflection(v any)
- func ReadOnly(r FileReader) ([]byte, error)
- func ReaderWriterExample()
- func ReturningInterfacesDemo()
- func RunAcceptReturnDemo()
- func RunConcurrencyExample()
- func SegregationDemo()
- func ShowAdapterPattern()
- func ShowDeprecatedFunction()
- func ShowV1()
- func ShowV2()
- func ShowV3()
- func SortData()
- func SortInterfaceExample()
- func StringSorter(r io.Reader) (string, error)
- func StructuralVsNominalTyping()
- func TestCreateUser()
- func TestDeleteUser()
- func TypeAssertionBasics()
- func TypeSwitchExample(value any)
- func UnsafeTypeAssertions(value interface{})
- func UseCounter(c Counter)
- func UseLogger(logger Loggable, message string)
- func UseShape(s Shape)
- func UsingGenericHolder()
- func UsingTypedHolder()
- func WriteOnly(w FileWriter, data []byte) error
- type Adder
- type AdvancedStorage
- type BadDatabaseClient
- type BadInterfaceEmbedding
- type BufferedWriteCloser
- type ByAge
- type ByName
- type CachingService
- type CalculationResult
- type Calculator
- type Circle
- type ClientV1
- type ClientV2
- type ClientV3
- type Closer
- type CombinedLogger
- type CombinedStorage
- type ConcreteReader
- type Config
- type Connectable
- type CorrectInterfaceEmbedding
- type Counter
- type CustomTime
- type DataProcessor
- type DataStore
- type DatabaseUserRepository
- type Describer
- type DisplayItem
- type Duck
- type EmailRecord
- type EmailService
- type EnhancedStorage
- type Event
- type File
- type FileCloser
- type FileInfo
- type FileManager
- type FilePermissionsManager
- type FileReadSeeker
- type FileReadWriteCloser
- type FileReadWriteSeeker
- type FileReadWriter
- type FileReader
- type FileSeeker
- type FileSyncer
- type FileTruncater
- type FileWriter
- type GenericContainer
- type GenericHolder
- type HelloHandler
- type Inconsistent
- type InconsistentImpl
- type InterfacePromise
- type Loggable
- type Logger
- type LoggerV1
- type LoggerV2
- type LoggingReader
- type MockEmailService
- type MockFile
- func (f *MockFile) Chmod(mode uint32) error
- func (f *MockFile) Chown(uid, gid int) error
- func (f *MockFile) Close() error
- func (f *MockFile) Read(p []byte) (int, error)
- func (f *MockFile) Seek(offset int64, whence int) (int64, error)
- func (f *MockFile) Stat() (FileInfo, error)
- func (f *MockFile) Sync() error
- func (f *MockFile) Truncate(size int64) error
- func (f *MockFile) Write(p []byte) (int, error)
- type MockUserRepository
- func (m *MockUserRepository) AddUser(user *User)
- func (m *MockUserRepository) Delete(id string) error
- func (m *MockUserRepository) FindByID(id string) (*User, error)
- func (m *MockUserRepository) GetDeleteCount() int
- func (m *MockUserRepository) GetFindCount() int
- func (m *MockUserRepository) GetSaveCount() int
- func (m *MockUserRepository) Save(user *User) error
- func (m *MockUserRepository) SetDeleteError(err error)
- func (m *MockUserRepository) SetFindError(err error)
- func (m *MockUserRepository) SetSaveError(err error)
- type Moveable
- type Mover
- type Multiplier
- type Order
- type Person
- type Point
- type Point2D
- type PointerReceiverOnly
- type Product
- type Quacker
- type Queryable
- type ReadWriteCloser
- type ReadWriter
- type Reader
- type ReaderToStringable
- type Rectangle
- type Result
- type SafeCounter
- type Service
- type Shape
- type SimpleProcessor
- type SimpleStorage
- type SimpleStore
- type SmtpEmailService
- type SortableString
- type SortableStringSlice
- type StatProvider
- type StorageAdapter
- type StorageV1
- type StorageV2
- type StorageV3
- type StorageV3Alt
- type StringReadWriteCloser
- type StringReadWriter
- type StringSource
- type Stringable
- type StringerValue
- type Transactional
- type TypedHolder
- type UnnecessaryRepositoryInterface
- type UnsafeCounter
- type User
- type UserRepository
- type UserService
- type ValueReceiverOnly
- type WebPage
- type Writer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AcceptReturnDemo ¶
func AcceptReturnDemo()
AcceptReturnDemo demonstrates the "accept interfaces, return structs" pattern
func AdvancedOperation ¶
func AdvancedOperation(rws FileReadWriteSeeker) error
AdvancedOperation requires more capabilities
func BadFactory ¶
BadFactory returns an interface, forcing the caller to work with a limited view
func BadFunction ¶
BadFunction uses empty interface unnecessarily - generally an anti-pattern
func BasicInterfaceDemo ¶
func BasicInterfaceDemo()
BasicInterfaceDemo demonstrates basic interface implementation in Go
func BetterFunction ¶
BetterFunction uses concrete types - preferred when possible
func CalculatorDemo ¶
func CalculatorDemo()
CalculatorDemo demonstrates the accept interfaces pattern with calculations
func Collection ¶
func Collection()
Collection demonstrates using empty interface for heterogeneous collections
func CopyData ¶
func CopyData(r FileReader, w FileWriter) (int, error)
CopyData accepts minimal interfaces needed for copying
func CustomSortExample ¶
func CustomSortExample()
CustomSortExample demonstrates implementing sort.Interface
func DemonstrateAntiPatterns ¶
func DemonstrateAntiPatterns()
DemonstrateAntiPatterns shows examples of interface anti-patterns
func DemonstrateStdlibInterfaces ¶
func DemonstrateStdlibInterfaces()
DemonstrateStdlibInterfaces shows all the standard library interface examples
func DisplayProperties ¶
func DisplayProperties(item DisplayItem)
DisplayProperties renders properties for any DisplayItem
func DuckTypingBasics ¶
func DuckTypingBasics()
DuckTypingBasics demonstrates basic duck typing in Go
func EmptyInterfaceDemo ¶
func EmptyInterfaceDemo()
EmptyInterfaceDemo demonstrates the empty interface and type assertions
func ExtendingInterfacesDemo ¶
func ExtendingInterfacesDemo()
ExtendingInterfacesDemo demonstrates extending standard library interfaces
func HttpHandlerExample ¶
func HttpHandlerExample()
HttpHandlerExample demonstrates the http.Handler interface
func IOCompositionExample ¶
func IOCompositionExample()
IOCompositionExample demonstrates interface composition
func InterfaceEmbeddingDemo ¶
func InterfaceEmbeddingDemo()
InterfaceEmbeddingDemo demonstrates embedding interfaces in structs
func InterfaceTestingDemo ¶
func InterfaceTestingDemo()
InterfaceTestingDemo demonstrates using interfaces for testing
func InterfaceUpgradeDemo ¶
func InterfaceUpgradeDemo()
InterfaceUpgradeDemo demonstrates interface upgrade patterns
func JSONInterfaceExample ¶
func JSONInterfaceExample()
JSONInterfaceExample demonstrates json.Marshaler and json.Unmarshaler
func LoggingMiddleware ¶
LoggingMiddleware wraps an http.Handler and logs each request
func MethodSetExample ¶
func MethodSetExample()
func MultiLevelCompositionDemo ¶
func MultiLevelCompositionDemo()
MultiLevelCompositionDemo demonstrates multi-level interface composition
func MultipleInterfacesDemo ¶
func MultipleInterfacesDemo()
MultipleInterfacesDemo demonstrates implementing multiple interfaces
func NilInterfaceDemo ¶
func NilInterfaceDemo()
NilInterfaceDemo demonstrates how nil values work with interfaces
func ParseValue ¶
ParseValue converts a string to various types using the empty interface
func PointerReceiverDemo ¶
func PointerReceiverDemo()
PointerReceiverDemo demonstrates interface implementation with pointer receivers
func PrintItems ¶
func PrintItems(items []Stringable)
PrintItems prints any slice of items that implement Stringable
func PrintReflection ¶
func PrintReflection(v any)
PrintReflection uses reflection to inspect a value of any type
func ReadOnly ¶
func ReadOnly(r FileReader) ([]byte, error)
ReadOnly accepts only a Reader, demonstrating that we can constrain functions to only require the minimal interface they need
func ReaderWriterExample ¶
func ReaderWriterExample()
ReaderWriterExample shows the power of the io.Reader and io.Writer interfaces
func ReturningInterfacesDemo ¶
func ReturningInterfacesDemo()
ReturningInterfacesDemo shows when it makes sense to return an interface
func RunAcceptReturnDemo ¶
func RunAcceptReturnDemo()
RunAcceptReturnDemo demonstrates all aspects of the "accept interfaces, return structs" pattern
func RunConcurrencyExample ¶
func RunConcurrencyExample()
RunConcurrencyExample demonstrates the difference between safe and unsafe implementations
func SegregationDemo ¶
func SegregationDemo()
SegregationDemo demonstrates the interface segregation principle
func ShowAdapterPattern ¶
func ShowAdapterPattern()
ShowAdapterPattern demonstrates the adapter pattern for interface upgrades
func ShowDeprecatedFunction ¶
func ShowDeprecatedFunction()
ShowDeprecatedFunction demonstrates upgrading with deprecated functions
func SortInterfaceExample ¶
func SortInterfaceExample()
SortInterfaceExample demonstrates the power of sort.Interface
func StringSorter ¶
StringSorter creates a function that sorts lines in a string
func StructuralVsNominalTyping ¶
func StructuralVsNominalTyping()
StructuralVsNominalTyping demonstrates the difference between Go's structural typing vs nominal typing in other languages
func TestCreateUser ¶
func TestCreateUser()
TestCreateUser demonstrates how to test with mock dependencies
func TestDeleteUser ¶
func TestDeleteUser()
TestDeleteUser demonstrates more advanced testing with mocks
func TypeAssertionBasics ¶
func TypeAssertionBasics()
TypeAssertionBasics demonstrates basic type assertions
func TypeSwitchExample ¶
func TypeSwitchExample(value any)
TypeSwitchExample demonstrates using type switches
func UnsafeTypeAssertions ¶
func UnsafeTypeAssertions(value interface{})
UnsafeTypeAssertions demonstrates dangerous type assertions
func UseCounter ¶
func UseCounter(c Counter)
func UseShape ¶
func UseShape(s Shape)
UseShape demonstrates using a function that accepts an interface
func UsingGenericHolder ¶
func UsingGenericHolder()
Usage requires type assertions and can lead to runtime errors
Types ¶
type AdvancedStorage ¶
type AdvancedStorage struct {
*EnhancedStorage // Embed V2 implementation
}
AdvancedStorage implements the V3 interface
func NewAdvancedStorage ¶
func NewAdvancedStorage() *AdvancedStorage
NewAdvancedStorage creates a new AdvancedStorage
func (*AdvancedStorage) DeleteWithContext ¶
func (s *AdvancedStorage) DeleteWithContext(ctx context.Context, key string) error
DeleteWithContext deletes a value with context support
func (*AdvancedStorage) GetWithContext ¶
GetWithContext gets a value with context support
func (*AdvancedStorage) SetWithContext ¶
SetWithContext sets a value with context support
type BadDatabaseClient ¶
type BadDatabaseClient interface { Connect(connectionString string) error Disconnect() error Query(query string) ([]byte, error) Execute(command string) error BeginTransaction() error CommitTransaction() error RollbackTransaction() error CacheResults(key string, data []byte) error GetFromCache(key string) ([]byte, error) ValidateSchema() error MigrateDatabase() error LogQuery(query string) error Authenticate(username, password string) error CheckPermissions(user string, resource string) bool }
BadDatabaseClient is an example of a "fat interface" - it has too many methods and combines multiple responsibilities.
type BadInterfaceEmbedding ¶
type BadInterfaceEmbedding struct { io.Writer // Embedding interface without implementing Write method // contains filtered or unexported fields }
BadInterfaceEmbedding embeds the io.Writer interface but doesn't implement its methods
type BufferedWriteCloser ¶
BufferedWriteCloser combines a buffered writer with a closer
func NewBufferedWriteCloser ¶
func NewBufferedWriteCloser(w io.WriteCloser, size int) *BufferedWriteCloser
NewBufferedWriteCloser creates a new BufferedWriteCloser
func (*BufferedWriteCloser) Close ¶
func (bwc *BufferedWriteCloser) Close() error
Close flushes the buffer and closes the underlying writer
type ByName ¶
type ByName []Person
ByName implements sort.Interface for []Person based on Name field
type CachingService ¶
type CachingService struct { DataStore // Interface embedding in struct // contains filtered or unexported fields }
CachingService embeds a DataStore interface This demonstrates embedding an interface inside a struct
func NewCachingService ¶
func NewCachingService(store DataStore) *CachingService
NewCachingService creates a new CachingService
func (*CachingService) CacheMisses ¶
func (c *CachingService) CacheMisses() int
CacheMisses returns the number of cache misses
type CalculationResult ¶
CalculationResult is a concrete return type
func PerformCalculation ¶
func PerformCalculation(calc Calculator, a, b int) *CalculationResult
PerformCalculation demonstrates the pattern with calculations
type Calculator ¶
Calculator defines calculation behavior
type Circle ¶
type Circle struct {
Radius float64
}
Circle is a concrete type that implicitly implements the Shape interface
type ClientV1 ¶
type ClientV1 struct {
// contains filtered or unexported fields
}
ClientV1 uses the V1 interface
type ClientV2 ¶
type ClientV2 struct {
// contains filtered or unexported fields
}
ClientV2 uses the V2 interface
type ClientV3 ¶
type ClientV3 struct {
// contains filtered or unexported fields
}
ClientV3 uses the V3 interface
type Closer ¶
type Closer interface {
Close() error
}
Closer is an interface for types that can be closed
type CombinedLogger ¶
type CombinedLogger struct {
// contains filtered or unexported fields
}
Implementation of both interfaces
func NewCombinedLogger ¶
func NewCombinedLogger(output io.Writer) *CombinedLogger
NewCombinedLogger creates a new CombinedLogger
func (*CombinedLogger) Log ¶
func (l *CombinedLogger) Log(message string)
Log implements LoggerV1.Log (deprecated)
func (*CombinedLogger) LogError ¶
func (l *CombinedLogger) LogError(err error)
LogError implements LoggerV1.LogError (deprecated)
func (*CombinedLogger) LogErrorWithLevel ¶
func (l *CombinedLogger) LogErrorWithLevel(level string, err error)
LogErrorWithLevel implements LoggerV2.LogErrorWithLevel
func (*CombinedLogger) LogWithLevel ¶
func (l *CombinedLogger) LogWithLevel(level string, message string)
LogWithLevel implements LoggerV2.LogWithLevel
type CombinedStorage ¶
type CombinedStorage struct { StorageV2 StorageV3Alt }
Wrapper to combine both V2 and V3Alt capabilities
type ConcreteReader ¶
type ConcreteReader struct {
// contains filtered or unexported fields
}
ConcreteReader is an implementation of io.Reader
func BetterFactory ¶
func BetterFactory() *ConcreteReader
BetterFactory returns a concrete type, giving callers access to all methods
func (*ConcreteReader) AdditionalMethod ¶
func (r *ConcreteReader) AdditionalMethod() string
AdditionalMethod is a useful method that's hidden when returning just an io.Reader
type Config ¶
Config demonstrates a simple configuration using map[string]any
type Connectable ¶
type CorrectInterfaceEmbedding ¶
type CorrectInterfaceEmbedding struct {
// contains filtered or unexported fields
}
CorrectInterfaceEmbedding properly embeds and implements the interface
type CustomTime ¶
CustomTime demonstrates implementing json.Marshaler and json.Unmarshaler
func (CustomTime) MarshalJSON ¶
func (ct CustomTime) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler for custom time formatting
func (*CustomTime) UnmarshalJSON ¶
func (ct *CustomTime) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler for custom time parsing
type DataProcessor ¶
DataProcessor represents something that can process data
func NewProcessor ¶
func NewProcessor(prefix string) DataProcessor
NewProcessor creates a new processor with the given prefix This function returns an interface, which is acceptable when: 1. You want to hide implementation details 2. You need polymorphic behavior determined at runtime
type DataStore ¶
type DataStore interface { Get(id string) ([]byte, error) Set(id string, data []byte) error Delete(id string) error }
DataStore defines the interface for data storage operations
type DatabaseUserRepository ¶
type DatabaseUserRepository struct {
// contains filtered or unexported fields
}
DatabaseUserRepository is a real implementation of UserRepository
func NewDatabaseUserRepository ¶
func NewDatabaseUserRepository(db DataStore) *DatabaseUserRepository
NewDatabaseUserRepository creates a new DatabaseUserRepository
func (*DatabaseUserRepository) Delete ¶
func (r *DatabaseUserRepository) Delete(id string) error
Delete removes a user from the database
func (*DatabaseUserRepository) FindByID ¶
func (r *DatabaseUserRepository) FindByID(id string) (*User, error)
FindByID retrieves a user from the database
func (*DatabaseUserRepository) Save ¶
func (r *DatabaseUserRepository) Save(user *User) error
Save stores a user in the database
type Describer ¶
type Describer interface {
Describe() string
}
Describer is an interface for types that can describe themselves
type DisplayItem ¶
DisplayItem is an interface that only requires Properties() method
type EmailRecord ¶
EmailRecord represents a sent email
type EmailService ¶
EmailService defines the interface for sending emails
type EnhancedStorage ¶
type EnhancedStorage struct { SimpleStorage // Embed V1 implementation // contains filtered or unexported fields }
EnhancedStorage implements the V2 interface
func NewEnhancedStorage ¶
func NewEnhancedStorage() *EnhancedStorage
NewEnhancedStorage creates a new EnhancedStorage
func (*EnhancedStorage) GetWithExpiration ¶
GetWithExpiration retrieves a value and its expiration time
func (*EnhancedStorage) List ¶
func (s *EnhancedStorage) List(prefix string) ([]string, error)
List returns all keys with the given prefix
func (*EnhancedStorage) SetWithExpiration ¶
func (s *EnhancedStorage) SetWithExpiration(key string, value []byte, expiration time.Duration) error
SetWithExpiration stores a value with an expiration time
type Event ¶
type Event struct { Title string `json:"title"` Time CustomTime `json:"time"` }
Event represents an event with a title and timestamp
type FileCloser ¶
type FileCloser interface {
Close() error
}
Closer is an interface for closing resources
type FileManager ¶
type FileManager interface { Read(p []byte) (n int, err error) Write(p []byte) (n int, err error) Seek(offset int64, whence int) (int64, error) Close() error Stat() (FileInfo, error) Chmod(mode uint32) error Chown(uid, gid int) error Truncate(size int64) error Sync() error }
FileManager is a monolithic interface that handles many different operations This violates interface segregation and is shown as an anti-pattern
type FilePermissionsManager ¶
FilePermissionsManager handles file permissions
type FileReadSeeker ¶
type FileReadSeeker interface { FileReader FileSeeker }
ReadSeeker combines read and seek capabilities
type FileReadWriteCloser ¶
type FileReadWriteCloser interface { FileReader FileWriter FileCloser }
ReadWriteCloser adds closing capability
type FileReadWriteSeeker ¶
type FileReadWriteSeeker interface { FileReader FileWriter FileSeeker }
ReadWriteSeeker combines read, write and seek capabilities
type FileReadWriter ¶
type FileReadWriter interface { FileReader FileWriter }
ReadWriter combines read and write capabilities
type FileReader ¶
Reader is an interface for reading data
type FileSeeker ¶
Seeker is an interface for seeking within a file
type FileSyncer ¶
type FileSyncer interface {
Sync() error
}
FileSyncer handles syncing file to disk
type FileTruncater ¶
FileTruncater handles file truncation
type FileWriter ¶
Writer is an interface for writing data
type GenericContainer ¶
type GenericContainer struct {
Value any // empty interface (interface{} in earlier Go versions)
}
GenericContainer demonstrates using the empty interface to store any type
func (GenericContainer) Print ¶
func (c GenericContainer) Print()
Print prints the container value, handling different types
type GenericHolder ¶
type GenericHolder struct {
// contains filtered or unexported fields
}
GenericHolder overuses empty interface
func NewGenericHolder ¶
func NewGenericHolder() *GenericHolder
func (*GenericHolder) Get ¶
func (h *GenericHolder) Get(key string) interface{}
func (*GenericHolder) Set ¶
func (h *GenericHolder) Set(key string, value interface{})
type HelloHandler ¶
type HelloHandler struct {
Greeting string
}
HelloHandler is a simple implementation of http.Handler
func (HelloHandler) ServeHTTP ¶
func (h HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
type Inconsistent ¶
type Inconsistent interface { Method1() Method2() }
Inconsistent is an example interface
type InconsistentImpl ¶
type InconsistentImpl struct {
// contains filtered or unexported fields
}
InconsistentImpl mixes pointer and value receivers
func (*InconsistentImpl) Method1 ¶
func (i *InconsistentImpl) Method1()
Method1 uses a pointer receiver
type InterfacePromise ¶
InterfacePromise represents a promise to provide data
type Loggable ¶
type Loggable interface {
Log(message string)
}
Loggable is an interface for anything that can log
type LoggerV2 ¶
type LoggerV2 interface { LogWithLevel(level string, message string) LogErrorWithLevel(level string, err error) }
Updated interface
type LoggingReader ¶
type LoggingReader struct {
// contains filtered or unexported fields
}
LoggingReader adds logging to any Reader
func NewLoggingReader ¶
func NewLoggingReader(r Reader, operation string) *LoggingReader
NewLoggingReader creates a new LoggingReader
type MockEmailService ¶
type MockEmailService struct {
// contains filtered or unexported fields
}
MockEmailService is a test double for EmailService
func NewMockEmailService ¶
func NewMockEmailService() *MockEmailService
NewMockEmailService creates a new MockEmailService
func (*MockEmailService) GetSentEmails ¶
func (m *MockEmailService) GetSentEmails() []EmailRecord
GetSentEmails returns all sent emails
func (*MockEmailService) SendEmail ¶
func (m *MockEmailService) SendEmail(to, subject, body string) error
SendEmail implements EmailService.SendEmail for testing
func (*MockEmailService) SetShouldError ¶
func (m *MockEmailService) SetShouldError(shouldErr bool)
SetShouldError configures whether the mock should return an error
type MockFile ¶
type MockFile struct {
// contains filtered or unexported fields
}
MockFile implements multiple interfaces through composition
func NewMockFile ¶
NewMockFile creates a new MockFile
type MockUserRepository ¶
type MockUserRepository struct {
// contains filtered or unexported fields
}
MockUserRepository is a test double for UserRepository
func NewMockUserRepository ¶
func NewMockUserRepository() *MockUserRepository
NewMockUserRepository creates a new MockUserRepository
func (*MockUserRepository) AddUser ¶
func (m *MockUserRepository) AddUser(user *User)
AddUser adds a user to the mock repository
func (*MockUserRepository) Delete ¶
func (m *MockUserRepository) Delete(id string) error
Delete implements UserRepository.Delete for testing
func (*MockUserRepository) FindByID ¶
func (m *MockUserRepository) FindByID(id string) (*User, error)
FindByID implements UserRepository.FindByID for testing
func (*MockUserRepository) GetDeleteCount ¶
func (m *MockUserRepository) GetDeleteCount() int
GetDeleteCount returns the number of times Delete was called
func (*MockUserRepository) GetFindCount ¶
func (m *MockUserRepository) GetFindCount() int
GetFindCount returns the number of times FindByID was called
func (*MockUserRepository) GetSaveCount ¶
func (m *MockUserRepository) GetSaveCount() int
GetSaveCount returns the number of times Save was called
func (*MockUserRepository) Save ¶
func (m *MockUserRepository) Save(user *User) error
Save implements UserRepository.Save for testing
func (*MockUserRepository) SetDeleteError ¶
func (m *MockUserRepository) SetDeleteError(err error)
SetDeleteError sets an error to be returned by Delete
func (*MockUserRepository) SetFindError ¶
func (m *MockUserRepository) SetFindError(err error)
SetFindError sets an error to be returned by FindByID
func (*MockUserRepository) SetSaveError ¶
func (m *MockUserRepository) SetSaveError(err error)
SetSaveError sets an error to be returned by Save
type Multiplier ¶
type Multiplier struct{}
Multiplier implements Calculator by multiplying numbers
func (Multiplier) Calculate ¶
func (m Multiplier) Calculate(x, y int) int
Calculate implements the Calculator interface
type Point ¶
type Point struct {
X, Y float64
}
Point is a struct representing a 2D point
func (Point) GetPosition ¶
GetPosition returns the current position
type PointerReceiverOnly ¶
type PointerReceiverOnly struct {
// contains filtered or unexported fields
}
PointerReceiverOnly has methods with pointer receivers
func (*PointerReceiverOnly) Count ¶
func (p *PointerReceiverOnly) Count() int
func (*PointerReceiverOnly) Increment ¶
func (p *PointerReceiverOnly) Increment()
type Quacker ¶
type Quacker interface {
Quack() string
}
Quacker is an interface for things that can quack
type ReadWriteCloser ¶
ReadWriteCloser composes three interfaces
type ReadWriter ¶
ReadWriter composes the Reader and Writer interfaces This is interface embedding - a fundamental form of composition in Go
type ReaderToStringable ¶
type ReaderToStringable struct { Name string // contains filtered or unexported fields }
Wrapper to adapt existing types to new interfaces
func (ReaderToStringable) ToString ¶
func (r ReaderToStringable) ToString() string
type Rectangle ¶
type Rectangle struct {
Width, Height float64
}
Rectangle is another concrete type that implicitly implements the Shape interface
type Result ¶
Result is a concrete type returned by our functions
func DataLoader ¶
func DataLoader(promise InterfacePromise) (*Result, error)
DataLoader loads data from a promise and transforms it
func ProcessData ¶
func ProcessData(processor DataProcessor, data string) *Result
ProcessData accepts an interface and returns a struct This demonstrates the "accept interfaces, return structs" pattern
type SafeCounter ¶
type SafeCounter struct {
// contains filtered or unexported fields
}
SafeCounter is safe for concurrent use
func (*SafeCounter) GetCount ¶
func (c *SafeCounter) GetCount() int
func (*SafeCounter) Increment ¶
func (c *SafeCounter) Increment()
type Shape ¶
type Shape interface {
Area() float64
}
Shape is a basic interface that defines a method for calculating area
type SimpleProcessor ¶
type SimpleProcessor struct {
// contains filtered or unexported fields
}
SimpleProcessor is a basic implementation of DataProcessor
func (SimpleProcessor) Process ¶
func (p SimpleProcessor) Process(data string) string
Process implements the DataProcessor interface
type SimpleStorage ¶
type SimpleStorage struct {
// contains filtered or unexported fields
}
SimpleStorage implements the V1 interface
func NewSimpleStorage ¶
func NewSimpleStorage() *SimpleStorage
NewSimpleStorage creates a new SimpleStorage
func (*SimpleStorage) Delete ¶
func (s *SimpleStorage) Delete(key string) error
Delete removes a value from storage
type SimpleStore ¶
type SimpleStore struct {
// contains filtered or unexported fields
}
SimpleStore is a basic implementation of DataStore
func (*SimpleStore) Get ¶
func (s *SimpleStore) Get(key string) (string, bool)
Get retrieves a value from the store
func (*SimpleStore) Set ¶
func (s *SimpleStore) Set(key, value string)
Set stores a value in the store
type SmtpEmailService ¶
type SmtpEmailService struct {
// contains filtered or unexported fields
}
SmtpEmailService is a real implementation of EmailService
func NewSmtpEmailService ¶
func NewSmtpEmailService(server string, port int, username, password string) *SmtpEmailService
NewSmtpEmailService creates a new SmtpEmailService
func (*SmtpEmailService) SendEmail ¶
func (s *SmtpEmailService) SendEmail(to, subject, body string) error
SendEmail sends an email via SMTP
type SortableString ¶
type SortableString string
SortableString is just a string that knows how to sort itself
type SortableStringSlice ¶
type SortableStringSlice []SortableString
We can implement sort.Interface methods on any type
func (SortableStringSlice) Len ¶
func (s SortableStringSlice) Len() int
func (SortableStringSlice) Less ¶
func (s SortableStringSlice) Less(i, j int) bool
func (SortableStringSlice) Swap ¶
func (s SortableStringSlice) Swap(i, j int)
type StatProvider ¶
StatProvider provides file information
type StorageAdapter ¶
type StorageAdapter struct {
// contains filtered or unexported fields
}
StorageAdapter adapts V2 to V3Alt
func NewStorageAdapter ¶
func NewStorageAdapter(v2 StorageV2) *StorageAdapter
NewStorageAdapter creates a new adapter
func (*StorageAdapter) DeleteWithContext ¶
func (a *StorageAdapter) DeleteWithContext(ctx context.Context, key string) error
DeleteWithContext implements StorageV3Alt
func (*StorageAdapter) GetWithContext ¶
GetWithContext implements StorageV3Alt
func (*StorageAdapter) SetWithContext ¶
SetWithContext implements StorageV3Alt
type StorageV1 ¶
type StorageV1 interface { Get(key string) ([]byte, error) Set(key string, value []byte) error Delete(key string) error }
StorageV1 is the first version of our storage interface
type StorageV2 ¶
type StorageV2 interface { StorageV1 // Embed V1 interface for backward compatibility GetWithExpiration(key string) ([]byte, time.Time, error) SetWithExpiration(key string, value []byte, expiration time.Duration) error List(prefix string) ([]string, error) }
StorageV2 extends StorageV1 with new capabilities
type StorageV3 ¶
type StorageV3 interface { // Keep original methods Get(key string) ([]byte, error) Set(key string, value []byte) error Delete(key string) error GetWithExpiration(key string) ([]byte, time.Time, error) SetWithExpiration(key string, value []byte, expiration time.Duration) error List(prefix string) ([]string, error) // Context-aware methods GetWithContext(ctx context.Context, key string) ([]byte, error) SetWithContext(ctx context.Context, key string, value []byte) error DeleteWithContext(ctx context.Context, key string) error }
StorageV3 adds context support to our storage interface
type StorageV3Alt ¶
type StorageV3Alt interface { GetWithContext(ctx context.Context, key string) ([]byte, error) SetWithContext(ctx context.Context, key string, value []byte) error DeleteWithContext(ctx context.Context, key string) error }
StorageV3Alt is a simpler interface that only defines new context methods
type StringReadWriteCloser ¶
type StringReadWriteCloser struct { StringReadWriter // contains filtered or unexported fields }
StringReadWriteCloser implements the ReadWriteCloser interface
func (*StringReadWriteCloser) Close ¶
func (s *StringReadWriteCloser) Close() error
Close implements the Closer interface
type StringReadWriter ¶
type StringReadWriter struct {
// contains filtered or unexported fields
}
StringReadWriter is a concrete type that implements the ReadWriter interface
type StringSource ¶
type StringSource struct {
// contains filtered or unexported fields
}
StringSource is a simple implementation of InterfacePromise
func (StringSource) Fulfill ¶
func (s StringSource) Fulfill() (string, error)
Fulfill implements the InterfacePromise interface
type Stringable ¶
type Stringable interface {
ToString() string
}
Stringable is an interface for anything that can be converted to a string
type StringerValue ¶
type StringerValue struct {
Data string
}
StringerValue is an example type that implements fmt.Stringer
type Transactional ¶
type TypedHolder ¶
type TypedHolder[T any] struct { // contains filtered or unexported fields }
TypedHolder uses generics for better type safety
func NewTypedHolder ¶
func NewTypedHolder[T any]() *TypedHolder[T]
func (*TypedHolder[T]) Get ¶
func (h *TypedHolder[T]) Get(key string) (T, bool)
func (*TypedHolder[T]) Set ¶
func (h *TypedHolder[T]) Set(key string, value T)
type UnnecessaryRepositoryInterface ¶
type UnnecessaryRepositoryInterface interface { GetUserByID(id int) (User, error) CreateUser(user User) error UpdateUser(user User) error DeleteUser(id int) error }
UnnecessaryRepositoryInterface is an example of an interface created unnecessarily before there are multiple implementations or a need for abstraction
type UnsafeCounter ¶
type UnsafeCounter struct {
// contains filtered or unexported fields
}
UnsafeCounter is not safe for concurrent use
func (*UnsafeCounter) GetCount ¶
func (c *UnsafeCounter) GetCount() int
func (*UnsafeCounter) Increment ¶
func (c *UnsafeCounter) Increment()
type UserRepository ¶
type UserRepository interface { FindByID(id string) (*User, error) Save(user *User) error Delete(id string) error }
UserRepository handles user data operations
func (*UserRepository) CreateUser ¶
func (r *UserRepository) CreateUser(user User) error
CreateUser adds a new user to storage
func (*UserRepository) DeleteUser ¶
DeleteUser removes a user from storage
func (*UserRepository) GetUserByID ¶
GetUserByID gets a user from storage
func (*UserRepository) UpdateUser ¶
func (r *UserRepository) UpdateUser(user User) error
UpdateUser updates an existing user
type UserService ¶
type UserService struct {
// contains filtered or unexported fields
}
UserService implements business logic for user operations
func NewUserService ¶
func NewUserService(repo UserRepository, email EmailService) *UserService
NewUserService creates a new UserService
func (*UserService) CreateUser ¶
func (s *UserService) CreateUser(username, email string) (*User, error)
CreateUser creates a new user and sends a welcome email
func (*UserService) DeleteUser ¶
func (s *UserService) DeleteUser(id string) error
DeleteUser deletes a user and sends a confirmation email
type ValueReceiverOnly ¶
type ValueReceiverOnly struct {
// contains filtered or unexported fields
}
ValueReceiverOnly has methods with value receivers
func (ValueReceiverOnly) Count ¶
func (v ValueReceiverOnly) Count() int