Documentation
¶
Overview ¶
Package base defines
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Embedded ¶ added in v0.29.0
Embedded returns the embedded BaseI structure of type T that is embedded in o.
T should be a pointer to the embedded structure and be public. The returned structure will bypass virtual functions that are defined in o and call functions directly on the embedded structure.
Will panic if T is not found in o.
Types ¶
type Base ¶
type Base struct {
// contains filtered or unexported fields
}
Base is a base structure to embed in objects that can call its functions as virtual functions.
Virtual functions are functions that provide a default implementation but that can be overridden by a subclass. For some, the lack of virtual function support in Go is a benefit, as some claim virtual functions contribute to poor architecture. However, for certain problems, they can be really helpful. They are especially helpful when you want to model a system that has default functionality, but you want to create similar items that have small changes to that functionality. Application frameworks are a good example of this.
To create such a structure, use the following pattern:
type Bird struct {
Base
}
// BirdI defines the virtual functions of Bird.
type BirdI interface {
BaseI
Call() string
}
func NewBird() *Bird {
b := new(Bird)
b.Init(b)
return b
}
func (a* Bird) PrintCall () {
fmt.Print(a.this().Call())
}
// Call can be overridden by a subclass.
func (a* Bird) Call () string {
return "chirp"
}
func (a* Bird) this() BirdI {
return a.Self().(BirdI)
}
type Duck struct {
Bird
}
type DuckI interface {
BirdI
}
func NewDuck() *Duck {
d := new(Duck)
d.Init(d)
return d
}
func (a* Duck) Call () string {
return "quack"
}
The following code will then print "quack":
NewDuck().PrintCall()
Be careful when using GobDecode() to restore an encoded object. To restore virtual function ability, you should call Init() on the object after it is decoded.
func (*Base) Init ¶
Init captures the object being passed to it so that virtual functions can be called on it.
type BaseI ¶
type BaseI interface {
// TypeOf returns the reflection type of the object. This allows superclasses to determine
// the type of the subclassing object. The type will not be a pointer to the type, but the type itself.
TypeOf() reflect.Type
// String returns a string representation of the object.
String() string
}
BaseI is an interface representing all objects that embed the Base struct.
It adds the ability for all such objects to get the object's type and a string representation of the object, which by default is the object's type. To be sure to get the object's type even if String() is overridden, use TypeOf().String().