Cursor rules for Go interfaces that stay small, live with their consumers, compose, are checked at compile time and have documented contracts and simple fakes.
.cursor/rules/go-interface-design.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for Go interfaces that stay small, live with their consumers, compose, are checked at compile time and have documented contracts and simple fakes."
globs: "**/*"
alwaysApply: false
---
# Go Interface Design
Applies to: Go packages that declare interfaces, accept dependencies, or perform type assertions.
Version baseline: checked against Go 1.27 and Effective Go. Snippets omit import blocks.
## 1. Keep interfaces small
- Declare only the methods the consumer calls. One- and two-method interfaces (`io.Reader`, `fmt.Stringer`) compose and are easy to fake.
- Name single-method interfaces after the method plus `-er` (`Notifier`, `UserGetter`) when that reads naturally.
- Do not add methods "for completeness"; each method is a burden on every implementation.
## 2. Accept interfaces, return concrete types
- Functions and constructors accept the narrow interface they need and return a concrete type (`*Store`), so callers get the full API and you can add methods without breaking anyone.
- Return an interface only when you deliberately hide multiple implementations behind it (for example `error`, or a constructor that picks an implementation at runtime).
## 3. Define interfaces where they are used
Put the interface in the consumer package, not next to the implementation. The implementation does not need to import or mention it.
```go
// package billing (consumer)
type CustomerGetter interface {
GetCustomer(ctx context.Context, id string) (Customer, error)
}
type Service struct{ customers CustomerGetter }
func NewService(c CustomerGetter) *Service { return &Service{customers: c} }
// package postgres (implementation) has *Store with GetCustomer and many other methods.
// It satisfies billing.CustomerGetter implicitly.
```
- Do not create an interface before there is a second implementation or a test that needs a fake.
## 4. Compose interfaces
Build larger interfaces by embedding small ones, as the standard library does with `io.ReadWriter`:
```go
type Reader interface{ Read(ctx context.Context, key string) ([]byte, error) }
type Writer interface{ Write(ctx context.Context, key string, v []byte) error }
type ReadWriter interface {
Reader
Writer
}
```
## 5. Check implementations at compile time
When a type must satisfy an interface it does not otherwise reference, add an assertion in the implementation package:
```go
var _ billing.CustomerGetter = (*Store)(nil)
```
## 6. Implement Stringer for readable output
Implement `String() string` on types that appear in logs and error messages (IDs, enums, money). Do not include secrets, and do not call `fmt.Sprint(x)` on the receiver inside `String`, which recurses.
```go
type Status int
const (
Pending Status = iota
Paid
)
func (s Status) String() string {
switch s {
case Pending:
return "pending"
case Paid:
return "paid"
default:
return fmt.Sprintf("Status(%d)", int(s))
}
}
```
## 7. Use type assertions with the ok form
- Write `v, ok := x.(T)` and handle `!ok`; the single-value form panics on mismatch.
- Use a type switch for several possible types.
- Use assertions to discover optional capabilities (for example `if f, ok := w.(http.Flusher); ok { f.Flush() }`), not to recover concrete types you control; if you need the concrete type, accept it directly.
- For errors, use `errors.As`/`errors.AsType` instead of asserting on `err` directly, because errors may be wrapped.
## 8. Document the contract
The method signature is not the whole contract. Document what implementations must guarantee: return values on "not found" (sentinel error or zero value), concurrency safety, whether the context must be honored, and ownership of returned slices.
```go
// CustomerGetter loads customers by ID.
// Implementations must return ErrCustomerNotFound (possibly wrapped) when no
// customer exists, must honor ctx cancellation, and must be safe for concurrent use.
```
## 9. Test with small fakes
Hand-written fakes are usually enough for one- or two-method interfaces; use a mock generator only if the project already does.
```go
type fakeCustomers map[string]Customer
func (f fakeCustomers) GetCustomer(_ context.Context, id string) (Customer, error) {
c, ok := f[id]
if !ok {
return Customer{}, ErrCustomerNotFound
}
return c, nil
}
```
## Verify before finishing
Run these when they are available in the project:
- `go vet ./...` and `go test ./...`
- `go build ./...` (compile-time interface assertions fail here)
- `staticcheck ./...` or `golangci-lint run`, if configured
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Go service has this rule attached while a developer asks Cursor to decouple a billing service from the Postgres store for testing.
billing.Service currently takes *postgres.Store, which has 30 methods. It only calls GetCustomer. Make Service testable without a database.
Illustrative; not a recorded model run. A one-method CustomerGetter interface declared in package billing with a doc comment stating the not-found error, ctx and concurrency contract; NewService accepting the interface and returning *Service; a var _ billing.CustomerGetter = (*Store)(nil) assertion in package postgres; a map-based fake in the billing tests; no interface added to the postgres package.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/go-interface-design.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Go Interface Design: Small, Consumer-Side and Documented project conventions"
globs: "**/*"
alwaysApply: false
---
# Go Interface Design
Applies to: Go packages that declare interfaces, accept dependencies, or perform type assertions.
Version baseline: checked against Go 1.27 and Effective Go. Snippets omit import blocks.
## 1. Keep interfaces small
- Declare only the methods the consumer calls. One- and two-method interfaces (`io.Reader`, `fmt.Stringer`) compose and are easy to fake.
- Name single-method interfaces after the method plus `-er` (`Notifier`, `UserGetter`) when that reads naturally.
- Do not add methods "for completeness"; each method is a burden on every implementation.
## 2. Accept interfaces, return concrete types
- Functions and constructors accept the narrow interface they need and return a concrete type (`*Store`), so callers get the full API and you can add methods without breaking anyone.
- Return an interface only when you deliberately hide multiple implementations behind it (for example `error`, or a constructor that picks an implementation at runtime).
## 3. Define interfaces where they are used
Put the interface in the consumer package, not next to the implementation. The implementation does not need to import or mention it.
```go
// package billing (consumer)
type CustomerGetter interface {
GetCustomer(ctx context.Context, id string) (Customer, error)
}
type Service struct{ customers CustomerGetter }
func NewService(c CustomerGetter) *Service { return &Service{customers: c} }
// package postgres (implementation) has *Store with GetCustomer and many other methods.
// It satisfies billing.CustomerGetter implicitly.
```
- Do not create an interface before there is a second implementation or a test that needs a fake.
## 4. Compose interfaces
Build larger interfaces by embedding small ones, as the standard library does with `io.ReadWriter`:
```go
type Reader interface{ Read(ctx context.Context, key string) ([]byte, error) }
type Writer interface{ Write(ctx context.Context, key string, v []byte) error }
type ReadWriter interface {
Reader
Writer
}
```
## 5. Check implementations at compile time
When a type must satisfy an interface it does not otherwise reference, add an assertion in the implementation package:
```go
var _ billing.CustomerGetter = (*Store)(nil)
```
## 6. Implement Stringer for readable output
Implement `String() string` on types that appear in logs and error messages (IDs, enums, money). Do not include secrets, and do not call `fmt.Sprint(x)` on the receiver inside `String`, which recurses.
```go
type Status int
const (
Pending Status = iota
Paid
)
func (s Status) String() string {
switch s {
case Pending:
return "pending"
case Paid:
return "paid"
default:
return fmt.Sprintf("Status(%d)", int(s))
}
}
```
## 7. Use type assertions with the ok form
- Write `v, ok := x.(T)` and handle `!ok`; the single-value form panics on mismatch.
- Use a type switch for several possible types.
- Use assertions to discover optional capabilities (for example `if f, ok := w.(http.Flusher); ok { f.Flush() }`), not to recover concrete types you control; if you need the concrete type, accept it directly.
- For errors, use `errors.As`/`errors.AsType` instead of asserting on `err` directly, because errors may be wrapped.
## 8. Document the contract
The method signature is not the whole contract. Document what implementations must guarantee: return values on "not found" (sentinel error or zero value), concurrency safety, whether the context must be honored, and ownership of returned slices.
```go
// CustomerGetter loads customers by ID.
// Implementations must return ErrCustomerNotFound (possibly wrapped) when no
// customer exists, must honor ctx cancellation, and must be safe for concurrent use.
```
## 9. Test with small fakes
Hand-written fakes are usually enough for one- or two-method interfaces; use a mock generator only if the project already does.
```go
type fakeCustomers map[string]Customer
func (f fakeCustomers) GetCustomer(_ context.Context, id string) (Customer, error) {
c, ok := f[id]
if !ok {
return Customer{}, ErrCustomerNotFound
}
return c, nil
}
```
## Verify before finishing
Run these when they are available in the project:
- `go vet ./...` and `go test ./...`
- `go build ./...` (compile-time interface assertions fail here)
- `staticcheck ./...` or `golangci-lint run`, if configured
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.