问题描述
package main
type Writeable interface {
OnWrite() interface{}
}
type Result struct {
Message string
}
func (r *Result) OnWrite() interface{} {
return r.Message
}
// what does this line mean? what is the purpose?
var _ Writeable = (*Result)(nil)
func main() {
}
代码段中的注释表达了我的困惑.据我了解,带有注释的行通知编译器检查结构是否实现了该接口,但是我不太确定.有人可以帮忙解释一下目的吗?
The comments in the code snippet expressed my confusion.As I understood, the line with comment notifies the compiler to check whether a struct has implemented the interface, but I am not sure very much. Could someone help explaining the purpose?
推荐答案
正如您所说,这是一种验证Result
实现Writeable
的方法.从 GO常见问题解答:
As you say it's a way to verify that Result
implements Writeable
. From the GO FAQ:
type T struct{}
var _ I = T{} // Verify that T implements I.
空白标识符_代表此处不需要的变量名(从而防止出现已声明但未使用"错误).
The blank identifier _ stands for the variable name which is not needed here (and thus prevents a "declared but not used" error).
(*Result)(nil)
通过转换 nil
到Result的值的未初始化指针>.这样可以避免像new(Result)
或&Result{}
那样为空结构分配内存.
(*Result)(nil)
creates an uninitialized pointer to a value of type Result
by converting nil
to *Result
. This avoids allocation of memory for an empty struct as you'd get with new(Result)
or &Result{}
.
这篇关于难以理解一段golang代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!