Ensure that type implements interface
suggest changeIn Go interfaces are satisfied implicitly. You don’t have to declare that a type is meant to implement a given interface.
That is convenient, but a type can fail to implement an interface and the compiler will not notice until a value of that type is used as the interface.
A compile-time check forces the mistake to be reported where the type is declared:
type MyReadCloser struct {
}
func (rc *MyReadCloser) Read(d []byte) (int, error) {
return 0, nil
}
var _ io.ReadCloser = &MyReadCloser{}
# test
./main.go:15:5: cannot use &MyReadCloser literal (type *MyReadCloser) as type io.ReadCloser in assignment:
*MyReadCloser does not implement io.ReadCloser (missing Close method)
exit status 2
Our intent was for MyReadCloser to implement io.ReadCloser interface.
However, we forgot to implement Close method.
This line caught this problem at compile time:
var _ io.ReadCloser = &MyReadCloser{}
We tried to assign *MyReadCloser type to variable of type io.ReadCloser.
Since *MyReadCloser doesn’t implement Close method, the compiler detected this is an invalid assignment at compile time.
We assigned the value to the blank identifier _ because we don’t use that variable for anything. The check uses *MyReadCloser because Read has a pointer receiver. A MyReadCloser value would not implement the interface either.