Compile Time Interface Satisfaction Check
Assert at compile time that a concrete type satisfies an interface with var _ Iface = (*T)(nil), so missing methods fail the build before deployment.
Code
package main
import "fmt"
// ArtifactStore 是配置层挑选后端实现时依赖的契约
type ArtifactStore interface {
Put(name string, blob []byte) error
Get(name string) ([]byte, error)
}
type memStore struct {
data map[string][]byte
limit int
}
// 编译期断言:*memStore 必须实现 ArtifactStore。
// 删掉或改名任一方法,构建立即失败,而不是等运行期类型断言才炸。
var _ ArtifactStore = (*memStore)(nil)
func newMemStore(limit int) *memStore {
return &memStore{data: make(map[string][]byte), limit: limit}
}
func (m *memStore) Put(name string, blob []byte) error {
if len(m.data) >= m.limit {
return fmt.Errorf("store full: limit %d", m.limit)
}
m.data[name] = blob
return nil
}
func (m *memStore) Get(name string) ([]byte, error) {
blob, ok := m.data[name]
if !ok {
return nil, fmt.Errorf("unknown artifact %q", name)
}
return blob, nil
}
func main() {
var store ArtifactStore = newMemStore(1)
if err := store.Put("svc.tar", []byte("v1.2.3")); err != nil {
panic(err)
}
blob, err := store.Get("svc.tar")
if err != nil {
panic(err)
}
fmt.Println("artifact:", string(blob))
}The one-line compile-time contract
var _ ArtifactStore = (*memStore)(nil) forces the compiler to prove *memStore implements both Put and Get today. Delete or rename either method and the build fails immediately — instead of a runtime type assertion discovering the gap after deployment. The nil value costs nothing at runtime; the line exists purely for the type checker.
The contract the store then keeps
Put enforces capacity first — if len(m.data) >= m.limit { return fmt.Errorf("store full: limit %d", m.limit) } — and Get reports absence as fmt.Errorf("unknown artifact %q", name) instead of a nil blob with nil error. main wires the interface, not the concrete type: var store ArtifactStore = newMemStore(1).
What the run prints
artifact: v1.2.3
store.Put("svc.tar", []byte("v1.2.3")) succeeds under the limit-1 store, store.Get("svc.tar") returns the same bytes, and both calls’ err checks pass before the print. Both error strings are reachable only when the guard arms fire — a full store or a missing name — which this particular run does not exercise.
The line that pins the interface
var _ ArtifactStore = (*memStore)(nil)
The blank identifier keeps the assertion anonymous; swap *memStore for any other candidate and the same single line audits that type too.
Interactive Tools for This Topic
FAQ
- How should callers handle failures?
- Through `error` values — the snippet checks `err != nil` at 2 sites, and the entry flow turns failures into `panic(err)`.
- What does Compile Time Interface Satisfaction Check print when run?
- No setup needed: run the file and look for labeled lines like `artifact:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.