什么是接口断言? [英] What is an interface assertion?

查看:2192
本文介绍了什么是接口断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在此博客文章

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 ...

这是什么接口断言?

推荐答案

它将具体类型的nil指针指定给接口类型的变量。这是一种常见的做法,用于证明具体类型满足接口 - 如果不满足,则该行不会编译,给出错误,即不能将具体类型分配给接口类型的变量以及原因。

It assigns a nil pointer to a concrete type to a variable of the interface type. This is a common practice to prove that the concrete type fulfills the interface - if it doesn't, that line won't compile, giving an error that the concrete type can't be assigned to a variable of the interface type and why.

正如@JimB所说,界面断言是由作者组成的术语。 Go没有这样的术语。具体来说,这是一个类型转换,转换 nil 指向 tmLogger 的指针,然后将键入的nil指针指定给空白标识符变量 Logger 。如果 * tmLogger 不满足 Logger ,则分配将无法编译;但是,在运行时,这不占用任何内存,因为它使用的是nil值。

As @JimB noted, "interface assertion" is a term made up by the author. Go has no such term. This is, specifically, a type conversion, converting nil to a pointer to tmLogger, then assigning the typed nil pointer to a blank identifier variable of the interface type Logger. If *tmLogger does not satisfy Logger, the assignment won't compile; but, at runtime, this takes no memory because it's using a nil value.

据推测,作者使用这个术语的单位测试意义上的断言比type assertionsense - 该行代码断言该类型实现了接口,如果没有,则该行将失败。

Presumably the author uses this term more in the unit-testing sense of "assertion" than the "type assertion" sense - that line of code asserts that the type implements the interface, and if it doesn't, the line will fail.

这篇关于什么是接口断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆