Embedded Interface and Type Assertions
This lesson explains how embedding the interfaces works like a charm and how a function is called depending upon the type of interface decided at runtime.
We'll cover the following...
Interface embedding interface(s)
An interface can contain the name of one (or more) interface(s), which is equivalent to explicitly enumerating the methods of the embedded interface in the containing interface.
For example, the interface File
contains all the methods of ReadWrite
and Lock
, in addition to a Close()
method:
type ReadWrite interface {
Read(b Buffer) bool
Write(b Buffer) bool
}
type Lock interface {
Lock()
Unlock()
}
type File interface {
ReadWrite
Lock
Close()
}
Detecting and converting the type of an interface variable
An interface type variable varI
can contain a value of any type; we must have a means to detect this dynamic type, which is the actual type of the value stored in the variable at run time. The dynamic type may vary during execution but is always ...