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
  • public or private is visible or not for package
  • 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package tree

import "fmt"

type Node struct {
Value int
Left, Right *Node
}

func (node Node) Print() {
fmt.Print(node.Value)
fmt.Println()
}

func (node *Node) SetValue(value int) {
node.Value = value
}

func CreateNode(value int) *Node {
return &Node{Value: value}
}

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
2
3
4
5
6
7
8
9
10
package tree

func (node *Node) Traverse() {
if node == nil {
return
}
node.Left.Traverse()
node.Print()
node.Right.Traverse()
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import "learngo/tree"

func main() {
var root tree.Node
root = tree.Node{Value: 3}
root.Left = &tree.Node{}
root.Right = &tree.Node{5, nil, nil}
root.Right.Left = new(tree.Node)
root.Left.Right = tree.CreateNode(2)

root.Traverse()
}

Now run it,

1
2
3
4
5
0
2
3
0
5

We got the results as expected.