Have trouble understanding a piece of golang code

好久不见. 提交于 2020-03-24 03:56:30

问题


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?


回答1:


As you say it's a way to verify that Result implements Writeable. From the 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.

The blank identifier _ stands for the variable name which is not needed here (and thus prevents a "declared but not used" error).

(*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{}.



来源:https://stackoverflow.com/questions/30701755/have-trouble-understanding-a-piece-of-golang-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!