2015-06-08 55 views
2
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() { 

} 

代码片段中的注释表达了我的困惑。 据我所知,带注释的行通知编译器检查结构是否实现了接口,但我不太确定。有人可以帮助解释目的吗?无法理解一段golang代码

+2

[这是什么变量声明与下划线,内联接口和赋值?](http://stackoverflow.com/questions/14202181/what-is-this-variable-declaration-with-underscore-inline-接口和 - assignme) – Volker

回答

8

正如您所说,这是一种验证Result实施Writeable的方法。从GO FAQ

你可以要求编译器检查类型T实现了 接口I通过尝试分配:

type T struct{} 
var _ I = T{} // Verify that T implements I. 

空白标识符_代表变量名,其在这里不需要(从而防止“声明但未使用”的错误)。

(*Result)(nil)创建了由convertingnil*Result一个未初始化的指针Result类型的值。这样可以避免为空结构分配内存,就像使用new(Result)&Result{}一样。