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.
It’s convenient but also makes it possible to not fully implement an interface by mistake and compiler has no way of detecting that.
There’s a way to a compile-type check for that:
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 assignement at compile time.
We assigned the value to blank identifier _
because we don’t actually use that variable for anything.