Junior — Middle
How can you determine if a specific class or object implements a certain interface?
sobes.tech AI
Answer from AI
In Go, interfaces are implemented implicitly: if a type implements all the methods of an interface, it is automatically considered to implement that interface.
To check whether a specific type implements an interface, you can use a type assertion or try to assign a value of that type to a variable of the interface type.
Example:
package main
import "fmt"
type Reader interface {
Read(p []byte) (n int, err error)
}
type MyReader struct {}
func (r MyReader) Read(p []byte) (n int, err error) {
return 0, nil
}
func main() {
var r Reader
var mr MyReader
// Check implementation via assignment
r = mr // if MyReader does not implement Reader, there will be a compile-time error
// Check via type assertion
if _, ok := interface{}(mr).(Reader); ok {
fmt.Println("MyReader implements the Reader interface")
} else {
fmt.Println("MyReader does not implement the Reader interface")
}
}
Thus, the Go compiler guarantees conformity to the interface, and at runtime, you can verify it using a type assertion.