The Go compiler checks whether the type implements the specified interface

The open source library will have some strange syntax like the following:

var _ io.Writer = (*myWriter)(nil)
var _ io.Writer = myWriter{
    
    }

At this time, it will be a little confused. This is actually the compiler checking whether the *myWriter type implements the io.Writer interface.

Let's look at an example:

package main

import "io"

type myWriter struct {
    
    

}

/*func (w myWriter) Write(p []byte) (n int, err error) {
	return
}*/

func main() {
    
    
    // 检查 *myWriter 类型是否实现了 io.Writer 接口
    var _ io.Writer = (*myWriter)(nil)

    // 检查 myWriter 类型是否实现了 io.Writer 接口
    var _ io.Writer = myWriter{
    
    }
}

After commenting out the Write function defined for myWriter, run the program:

src/main.go:14:6: cannot use (*myWriter)(nil) (type *myWriter) as type io.Writer in assignment:
	*myWriter does not implement io.Writer (missing Write method)
src/main.go:15:6: cannot use myWriter literal (type myWriter) as type io.Writer in assignment:
	myWriter does not implement io.Writer (missing Write method)

Error message: *myWriter/myWriter does not implement the io.Writer interface, that is, the Write method is not implemented.

After uncommenting, no error is reported when running the program.

In fact, the above assignment statement will undergo implicit type conversion. During the conversion process, the compiler will check whether the type on the right side of the equal sign implements the function specified by the interface on the left side of the equal sign.

If you want to learn more Go language grammar and common knowledge points of Go language at work, you can refer to my note source code https://github.com/qiuyunzhao/go_basis

Guess you like

Origin blog.csdn.net/QiuHaoqian/article/details/107860984