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() {
}
代码片段中的注释表达了我的困惑。 据我了解,带有注释的行通知编译器检查结构是否已实现接口(interface),但我不太确定。谁能帮忙解释一下用途?
最佳答案
正如您所说,这是一种验证Result
实现Writeable
的方法。来自GO FAQ :
You can ask the compiler to check that the type T implements the interface I by attempting an assignment:
type T struct{} var _ I = T{} // Verify that T implements I.
空白标识符 _ 代表此处不需要的变量名(因此可以防止“已声明但未使用”错误)。
(*Result)(nil)
通过 converting 创建一个指向 Result
类型值的未初始化指针nil
到 *Result
。这避免了像使用 new(Result)
或 &Result{}
那样为空结构分配内存。
关于methods - 难以理解一段 golang 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30701755/