Interface guard is a pattern for compile-time checking that a type implements an interface.
1// Interface2type Repository interface {3 FindByID(id int) (*User, error)4 Save(user *User) error5 Delete(id int) error6}78// Implementation9type PostgresRepo struct {10 db *sql.DB11}1213func (r *PostgresRepo) FindByID(id int) (*User, error) { ... }14func (r *PostgresRepo) Save(user *User) error { ... }15func (r *PostgresRepo) Delete(id int) error { ... }1617// Interface guard: compiler checks implementation18var _ Repository = (*PostgresRepo)(nil)1920// If PostgresRepo doesn't implement Repository — compilation error!2122// Additionally: check interface consistency23var (24 _ Repository = (*PostgresRepo)(nil)25 _ Repository = (*MockRepo)(nil) // Must also implement it26)2728// Standard library uses this pattern29// io.ReadWriter is checked via:30var _ io.ReadWriter = (*os.File)(nil)
Advantages: