methods - 难以理解一段 golang 代码

标签 methods go interface

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/

相关文章:

java - Android:点击按钮后应用程序崩溃

java - Java,另一个方法内部的方法声明?

mongodb - 更新mongodb并返回已完全更改的内容?

go - Go 如何对常量进行算术运算?

algorithm - 如何在golang中签署curve25519 key ?

java - 类关系强类型化的最佳模式

java - 如何解决java聚合中的错误输出错误?

java - 如何将一种方法的结果作为另一种方法的参数

java - 在接口(interface)的所有子类中施加静态变量

c++ - 如何从实现与其他接口(interface)共享的接口(interface)的类继承