Embedded Interface and Type Assertions
Explore how to embed interfaces within other interfaces in Go and how to use type assertions to detect and convert dynamic types in interface variables. Understand both unchecked and safe type assertion methods and see examples of their usage to manage interface types effectively.
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 ...