Fragment Description:



Checking whether an instance of a Type implements an Interface.
That is one of the questions you will have to answer in maintaining applications.
The idiom 'var _ Jedi' = &Leo is useful to achieve a correct answer.
We are declaring a named variable with _ (underscore), of Type Jedi (a specific Interface).
This indicates we are not interested in the variable name and value.
In order for this fragment to compile, the referenced Struct must satisfy the Jedi interface.
Comment the Knight's method that implements it, the compilation will fail.
A Go 'interface' is two things:
it is a set of methods, but it is also a type.
.
A type implements an interface by implementing the method(s) of the interface.
Implication:
creating abstractions by considering the functionality/behavior that is common between datatypes, instead of considering the fields that are common between datatypes.
A must...
to read:
'http://golang.org/doc/effective_go.html#interfaces_and_types'.


isItImplementingInterface

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:34

/* ... <== see fragment description ... */

package main

type Jedi interface {
    HasForce() bool
}

// Knight implements the Jedi interface
type Knight struct {
}

// Comment this function, and this program will not compile anymore
func (k *Knight) HasForce() bool {
    return true
}
func main() {
    // Leo is a Knight
    Leo := Knight{}
    // Let's confirm he satisfies the Jedi interface (OK-> no compilation error)
    var _ Jedi = &Leo

}

/* Expected Output:
There should be no compiler error!
See what you get if you comment:
// func (k *Knight) HasForce() bool {
// return true
// }
like this!
*/



Comments