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() {

}

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?

holys
  • 13,869
  • 15
  • 45
  • 50
  • 2
    possible duplicate of [What is this variable declaration with underscore, inline interface and assignment?](http://stackoverflow.com/questions/14202181/what-is-this-variable-declaration-with-underscore-inline-interface-and-assignme) – Volker Jun 08 '15 at 07:28

1 Answers1

7

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

IamNaN
  • 6,654
  • 5
  • 31
  • 47