Go Programming Languages - OOP
Go's support about OOP
Go only supports encapsulation, does not support inheritance and polymorphism. Go only has struct, does not has class (like C programming language)
struct: how to create an instance
1 | type treeNode struct { |
factory function (a difference between Go and C++)
1 | // we do not need to care |
Question: was the variable created on stack or heap (a question that is important in C++ languages) Answer: not important! The compiler will decide if it is allocated on stack or heap
Define methods for struct
1 | // the parenthesis after func is called `receiver` |
The difference is, no matther what you decide: treeNode or treeNode *, both of them can be used in struct methods as needed. For example, even if you input an address of treenode:
1 | func (node treeNode) print() { |
This will also print root value because even if we pass an address, it will convert to a copy of the tree and then print it. The compiler is very smart and can convert according to the definition of the function.
The difference between treeNode
and
treeNode *
is that the treeNode
does not allow
changing the object (it creates a copy), while treeNode *
can change the value of the object.
Go Programming Languages - OOP