> For the complete documentation index, see [llms.txt](https://denglj.gitbook.io/essential-go/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://denglj.gitbook.io/essential-go/11-interfaces/ensure-that-type-implements-interface.md).

# 确认某类型已实现某接口

在Go中，接口是被隐式实现的，您不需要显式声明某类型要实现某接口。

这很方便，但当我们没有完全实现某接口时，编译器没法检查出这种错误。

这有一种方法可以进行编译类型检查：

```go
type MyReadCloser struct {
}

func (rc *MyReadCloser) Read(d []byte) (int, error) {
	return 0, nil
}

var _ io.ReadCloser = &MyReadCloser{}
```

编译上述代码会报出如下错误：

```go
./prog.go:15:5: cannot use &MyReadCloser literal (type *MyReadCloser) as type io.ReadCloser in assignment:
	*MyReadCloser does not implement io.ReadCloser (missing Close method)
```

我们打算让`MyReadCloser`结构体实现`io.ReadCloser`接口。但是，我们忘记了实现`Close`方法。

下面这行代码会在编译时就发现问题：

```go
var _ io.ReadCloser = &MyReadCloser{}
```

我们打算把\*MyReadCloser类型的值赋值给io.ReadCloser类型的变量。

因为\*MyReadCloser类型并没有实现Close方法，编译器就会在编译时发现无效的赋值操作。

我们把值赋给[*空白标识符*(blank identifier)](/essential-go/03-variables/blank-identifier.md) `_` ，是因为我们不会用这个变量做任何事情。
