Interface — defines behavior through method signatures, enabling polymorphism. Struct — defines data through named fields, providing concrete implementations.
Interfaces are implicitly satisfied in Go — if a type has all the required methods, it implements the interface. No declaration needed. This enables loose coupling and easy testing.
1type Cache interface {2 Get(key string) (interface{}, bool)3 Set(key string, value interface{})4}56type LRUCache struct {7 items map[string]interface{}8 cap int9}10func (c *LRUCache) Get(key string) (interface{}, bool) {11 v, ok := c.items[key]12 return v, ok13}14func (c *LRUCache) Set(key string, value interface{}) {15 c.items[key] = value16}
Structs are concrete types with named fields. You attach methods to them and can embed other structs for composition.
1type Config struct {2 Debug bool3 Port int4}
When to use:
Common mistakes:
any — loses type safety.