Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an underscore and interface name after keyword var mean?

From http://golang.org/src/pkg/database/sql/driver/types.go:

type ValueConverter interface {     // ConvertValue converts a value to a driver Value.     ConvertValue(v interface{}) (Value, error) }  var Bool boolType  type boolType struct{}  var _ ValueConverter = boolType{} // line 58  func (boolType) String() string { return "Bool" }  func (boolType) ConvertValue(src interface{}) (Value, error) {....} 

I known that ValueConverter is an interface name. Line 58 seems to declare that boolType implement interface ValueConverter, but is that necessary? I deleted line 58 and the code works well.

like image 680
dilfish Avatar asked Nov 02 '12 11:11

dilfish


1 Answers

It provides a static (compile time) check that boolType satisfies the ValueConverter interface. The _ used as a name of the variable tells the compiler to effectively discard the RHS value, but to type-check it and evaluate it if it has any side effects, but the anonymous variable per se doesn't take any process space.

It is a handy construct when developing and the method set of an interface and/or the methods implemented by a type are frequently changed. The construct serves as a guard against forgetting to match the method sets of a type and of an interface where the intent is to have them compatible. It effectively prevents to go install a broken (intermediate) version with such omission.

like image 165
zzzz Avatar answered Sep 30 '22 11:09

zzzz