Embedding
We have reviewed two methods to extend packages in Go:
- Composition
- Use alternative names
There’s another way to extend the built-in data type with embedding, which is kinda similar to inheritance in Java.
Let’s refactor the myTreeNode
code
1 | type myTreeNode struct { |
Run the code above, we got the same outputs:
1 | In Order |
Shadowed Method
We could “overload” the Traverse
method in entry.go
file
1 | func (myNode *myTreeNode) Traverse(){ |
When we invoke the Traverse
method, it will output the overloaded method:
1 | In Order |
To invoke the original method, we should use root.Node.Traverse()
instead.
Compared to composition method, using embedding is a syntax candy which can save lines of code.