Most object-oriented languages make you declare that a type implements an interface: you write implements SomeInterface, and the compiler ties the two together by name. In Go, a type satisfies an interface automatically, just by having the right methods. The type never mentions the interface, so the two stay decoupled, and that shapes how Go code is structured and how easy it is to maintain.
What is an interface
An interface is an abstract type that describes behavior. It lists a set of method signatures (names, parameter types and return types) without providing any implementation.
The two best-known interfaces in Go's standard library come from the io package:
// from package iotype Reader interface { Read(p []byte) (n int, err error)}type Writer interface { Write(p []byte) (n int, err error)}Any type with a Read method matching that signature satisfies io.Reader. Any type with the matching Write satisfies io.Writer. Files, network connections, HTTP request bodies, gzip compressors, and in-memory buffers all implement one or both. None of them declares it; they just have the right methods.
A simpler example is fmt.Stringer, which any type can satisfy by implementing a single method:
// from package fmttype Stringer interface { String() string}An interface says: "any type that has these methods qualifies." It makes no statement about how those methods are implemented, what other methods the type might have, or how the type stores its data.
Implicit satisfaction
In Go, a type satisfies an interface simply by implementing all of its methods. Go has no implements keyword and no registration step:
type Temperature struct { Celsius float64}func (t Temperature) String() string { return fmt.Sprintf("%.1f°C", t.Celsius)}Temperature satisfies Stringer because it has a String() string method. The Go compiler verifies this automatically wherever a Stringer is expected. You never have to tell Go that Temperature is a Stringer.
This is called structural typing or duck typing: if it has the right shape, it fits.
A type can satisfy multiple interfaces
Nothing stops a type from satisfying many interfaces at once. As long as it has all the methods each interface requires, it qualifies for all of them:
type File struct { name string // ...}func (f *File) Read(p []byte) (n int, err error) { return }func (f *File) Write(p []byte) (n int, err error) { return }func (f *File) Close() error { return nil }func (f *File) String() string { return f.name }*File satisfies io.Reader (has Read), io.Writer (has Write), io.Closer (has Close), and Stringer (has String) at the same time, without declaring any of them. You can pass a *File to any function that expects any of those interfaces.
Interfaces make code maintainable
Interfaces pay off most in how you structure a program. A function that accepts an interface instead of a concrete type doesn't care how that interface is implemented.
Consider a data layer that needs to query records:
type Database interface { Query(query string, args ...any) ([]Row, error) Insert(record Record) error Delete(id int) error}A function that accepts Database will work correctly regardless of whether the underlying implementation uses PostgreSQL, MySQL, SQLite, or an in-memory store for tests:
func GetUser(db Database, id int) (User, error) { rows, err := db.Query("SELECT * FROM users WHERE id = ?", id) if err != nil { return User{}, err } // ...}Each implementation provides the same set of operations:
type PostgresDB struct{ conn *sql.DB }func (p *PostgresDB) Query(q string, args ...any) ([]Row, error) { return nil, nil // postgres logic}func (p *PostgresDB) Insert(record Record) error { return nil }func (p *PostgresDB) Delete(id int) error { return nil }type InMemoryDB struct{ records map[int]Record }func (m *InMemoryDB) Query(q string, args ...any) ([]Row, error) { return nil, nil // in-memory logic}func (m *InMemoryDB) Insert(record Record) error { return nil }func (m *InMemoryDB) Delete(id int) error { return nil }GetUser does not change when you swap implementations. Neither does any other function written against Database. You can introduce a new database engine, or replace the real database with an in-memory version in tests, without touching the code that uses it.
Embedding interfaces
Just as structs can embed other structs, interfaces can embed other interfaces. The result is an interface whose method set is the union of all embedded interfaces:
type Reader interface { Read(p []byte) (n int, err error)}type Writer interface { Write(p []byte) (n int, err error)}type ReadWriter interface { Reader Writer}ReadWriter requires both Read and Write. Any type that implements both satisfies ReadWriter. The standard library uses this pattern a lot: io.ReadWriter, io.ReadWriteCloser and io.ReadWriteSeeker are all composed from smaller interfaces.
With embedding you build interface contracts out of small pieces. A function that only reads can require Reader, and a function that reads and writes can require ReadWriter, so each one asks only for the methods it calls.
The empty interface
An interface with no methods is satisfied by every type in Go. It has no requirements, so nothing can fail to meet them:
var x interface{}x = 42x = "hello"x = truex = []int{1, 2, 3}Because this pattern is so common, Go 1.18 introduced any as a predeclared alias for interface{}. The two are identical. You can use either, and any is the modern convention:
var x anyx = 42x = "hello"The empty interface is useful when you need to accept or store values whose type is unknown or varies: a generic container, a JSON deserializer, a logger that accepts arbitrary values. It is also the type of the elements returned by reflection.
Nil interfaces
An interface value is a pair: a pointer to type information and a pointer to the concrete value. Go represents this internally as:
type iface struct { tab *itab // type information data unsafe.Pointer // the value}An interface is nil only when both pointers are nil. A freshly declared interface variable has neither type nor value, so it is nil:
var err errorfmt.Println(err == nil) // trueThe trap appears when you assign a nil concrete pointer to an interface:
var p *MyError = nilvar err error = pfmt.Println(err == nil) // falseEven though p itself is nil, assigning it to err fills the tab field with *MyError type information. The interface now knows its concrete type, so it is not nil, even though the underlying pointer is.
Go works this way because the runtime needs the type to dispatch method calls. Without tab, it could not know which Error() method to call.
This shows up most often in functions that return an error. Returning a nil pointer of a concrete error type is not the same as returning nil:
// returns a non-nil interface holding a nil pointerfunc validate() error { var e *ValidationError = nil return e}The safe approach is to return an untyped nil directly:
func validate() error { return nil}If you need to conditionally return a typed error, check the concrete value first:
func validate() error { var e *ValidationError = nil if e == nil { return nil } return e}When an interface comparison with nil gives an unexpected result, print the dynamic type and value separately:
fmt.Printf("%T %v\n", err, err)// *main.MyError <nil> ← interface is not nil, but its value isType assertion
When you have a value stored in an interface and need to recover the concrete type underneath, you use a type assertion. A type assertion doesn't convert anything: it gives you back the value with the concrete type that was stored in the interface:
var x any = "hello"s := x.(string) // asserts that x holds a stringfmt.Println(s) // helloIf the interface holds a different type, Go panics at runtime:
var x any = 42// panic: interface conversion: interface {} is int, not strings := x.(string)To avoid a panic, use the two-value form. The second return value is a boolean that reports whether the assertion succeeded:
var x any = 42s, ok := x.(string)if ok { fmt.Println("string:", s)} else { fmt.Println("not a string") // this branch runs}Type switch
When you need to handle several possible concrete types stored in an interface, a type switch is cleaner than a chain of type assertions. A type switch looks like a regular switch, but the case expressions are types rather than values:
func describe(x any) string { switch v := x.(type) { case int: return fmt.Sprintf("int: %d", v) case string: return fmt.Sprintf("string: %q", v) case bool: return fmt.Sprintf("bool: %v", v) case []int: return fmt.Sprintf("[]int with %d elements", len(v)) default: return fmt.Sprintf("unknown type: %T", v) }}The syntax x.(type) is only valid inside a switch statement. Inside each case, the variable v is automatically typed to the matched type. In the int case, v is an int; in the string case, v is a string. In the default case, v remains any.
fmt.Println(describe(42)) // int: 42fmt.Println(describe("hello")) // string: "hello"fmt.Println(describe(true)) // bool: truefmt.Println(describe([]int{1,2,3})) // []int with 3 elementsfmt.Println(describe(3.14)) // unknown type: float64A type switch is the idiomatic way to branch on a value's type at runtime in Go. You will see it often in code that handles values from external sources, such as JSON decoders, RPC frameworks and loggers, where the concrete type is only known at runtime.