Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the compile-time interface check idiom and why is it important?
Because Go interface satisfaction is implicit, the compiler normally checks it only at the point of actual use (assignment or function call). If a type is exported and expected to satisfy an interface, a change to the type's method set might silently break the contract — only catching the error at the site of use, not at the site of definition.
The compile-time check idiom prevents this:
// Idiom: assign nil pointer of the type to an interface variable // This costs nothing at runtime (no allocation) but fails to compile // if the interface is not satisfied. type MyStore struct{ /* ... */ } func (m *MyStore) Get(key string) (string, error) { /* ... */ return "", nil } func (m *MyStore) Set(key, val string) error { /* ... */ return nil } func (m *MyStore) Delete(key string) error { /* ... */ return nil } type Cache interface { Get(key string) (string, error) Set(key, val string) error Delete(key string) error } // Compile-time check â placed right after the type definition var _ Cache = (*MyStore)(nil) // fails to compile if *MyStore doesn't satisfy Cache // Alternatively, for value receivers: var _ Cache = MyStore{} // check value type // This check is also useful in test files: // var _ http.Handler = (*MyHandler)(nil) // var _ sort.Interface = ByAge(nil) // What error you get on failure: // cannot use (*MyStore)(nil) (type *MyStore) as type Cache in assignment: // *MyStore does not implement Cache (missing Delete method)
The idiom is especially important for exported types in libraries: the check serves as documentation ("this type is intended to implement Cache") and as a regression guard. If a developer accidentally removes a method or changes its signature, the check immediately fails with a clear error pointing to the problem.
More Related questions...