Go Encapsulation
Time to review how to encapsulate methods.
Encapsulation
- Go usually adopts CamelCases for naming.
- If the first letter is in upper case, this method is
public - If the first letter is in lower case, this method is
private publicorprivateis visible or not forpackage- Each folder is a package, unlike Java, the folder name is not necessarily the package name
- Each folder can only have one package
- main package contains the entry for execution
- All struct methods must be placed in the same package, yet could be saved in different files
Refactor Treenode
Let’s reorgnize the folder as below:
Then we need to refactor the code as following:
Package
The package is called tree, it has two files and a sub-folder containing entry point for main.
Node file
In the Node file:
1 | package tree |
Note all values and functions are capitalized for public use.
traverse file
Methods don’t have to be in the same file, we can create a traverse.go file to hold Traverse method.
1 | package tree |
entry folder
In the entry sub-folder, we have an entry.go file. We have a sub-folder because each folder can only have one package.
1 | package main |
Now run it,
1 | 0 |
We got the results as expected.