Junior — Middle
What are the consequences if a data structure does not implement the specified interface in object-oriented programming?
sobes.tech AI
Answer from AI
In Go, interfaces are implemented implicitly: if a struct contains all the methods of an interface, it implements that interface. If a struct does not implement the specified interface, then:
- The compiler will produce an error when attempting to use this struct as a value of the interface type.
- This prevents runtime errors, as Go strictly checks for interface compliance at compile time.
For example, if you have an interface:
type Reader interface {
Read(p []byte) (n int, err error)
}
And a struct:
type MyStruct struct {}
// No Read method, so MyStruct does not implement Reader
Attempting to assign a MyStruct to a variable of type Reader will result in a compile-time error.
Thus, if a struct does not implement an interface, you cannot use it where that interface is expected, which helps avoid logical errors in the program.