Reputation: 14769
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?
Upvotes: 4
Views: 267
Reputation: 6864
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{}
.
Upvotes: 8