什么是接口断言?

What is an interface assertion?

我刚刚在 this blog post

上看到这段代码
type Logger interface {
    Debug(msg string, keyvals ...interface{}) error
    Info(msg string, keyvals ...interface{}) error
    Error(msg string, keyvals ...interface{}) error
}

type tmLogger struct {
    srcLogger kitlog.Logger
}

// Interface assertions
var _ Logger = (*tmLogger)(nil) // What is this?

// ... interface definition ...

这是什么"interface assertion"?

它将一个指向具体类型的nil指针赋值给一个接口类型的变量。这是证明具体类型满足接口的常见做法 - 如果不满足,则该行将无法编译,并给出无法将具体类型分配给接口类型变量的错误以及原因。

正如@JimB 指出的那样,"interface assertion" 是作者编造的术语。 Go 没有这样的术语。具体来说,这是接口类型 Loggertype conversion, converting nil to a pointer to tmLogger, then assigning the typed nil pointer to a blank identifier 变量。如果 *tmLogger 不满足 Logger,则赋值不会编译;但是,在运行时,这不会占用内存,因为它使用的是 nil 值。

据推测,作者更多地在 "assertion" 的单元测试意义上使用此术语,而不是 "type assertion" 的意义 - 该行代码断言该类型实现了接口,如果它没有' t,该行将失败。

鉴于这纯粹是一种测试实践,我个人将这些检查放在 _test.go 文件中,以便它们包含在单元测试执行中,从最终二进制文件中排除,并且显然是测试套件的一部分而不是应用程序逻辑。