I am new to Go programming language and recently encountered the following code:
func (rec *ContactRecord) Less(other interface{}) bool {
return rec.sortKey.Le
An interface
variable can hold values of any type that provides methods with the signatures from the interface declaration. Since interface{}
doesn't specify any methods, such a variable can store values of any type.
The method then goes on to use a type assertion to check that other
is actually a *ContactRecord
value (it will panic otherwise).
You might then ask why the method isn't declared as taking a *ContactRecord
argument then. The most likely reason is so that the *ContactRecord
type implements some interface with a Less
method with that signature.
Go uses interfaces for generalization of types. So if you want a function that takes a specific interface you write
func MyFunction(t SomeInterface) {...}
Every type that satisfies SomeInterface
can be passed to MyFunction
.
Now, SomeInterface
can look like this:
type SomeInterface interface {
SomeFunction()
}
To satisfy SomeInterface
, the type implementing it must implement SomeFunction()
.
If you, however, require an empty interface (interface{}
) the object does not need to
implement any method to be passed to the function:
func MyFunction(t interface{}) { ... }
This function above will take every type as all types implement the empty interface.
Now that you can have every possible type, the question is how to get the type back that was actually put in before. The empty interface does not provide any methods, thus you can't call anything on such a value.
For this you need type assertions: let the runtime check whether there is type X in value Y and convert it to that type if so.
Example:
func MyFunction(t interface{}) {
v, ok := t.(SomeConcreteType)
// ...
}
In this example the input parameter t
is asserted to be of type SomeConcreteType
. If t
is in fact of type SomeConcreteType
, v
will hold the instance of that type and ok
will
be true. Otherwise, ok
will be false. See the spec on type assertions for details.