- 每个目录一个包
- main包包含可执行入口
- 为结构定义的方法必须放在同一个包内
- 为结构定义的方法必须放在同一个包内
- 可以是不同文件
node.go
package tree
import "fmt"
type TreeNode struct {
Value int
Left, Right *TreeNode
}
func (node TreeNode) Print() {
fmt.Print(node.Value)
fmt.Print(" ")
}
func (node *TreeNode) SetValue(value int) {
if node == nil {
fmt.Println("setting value to nil node,ignored")
}
node.Value = value
}
func (node *TreeNode) Traverse() {
if node == nil {
return
}
node.Left.Traverse()
node.Print()
node.Right.Traverse()
}
func createNode(value int) *TreeNode {
return &TreeNode{Value: value}
}
entry.go
package main
import "go_code/project04/tree"
func main() {
var root tree.TreeNode
// fmt.Println(root)
root = tree.TreeNode{Value: 3}
root.Left = &tree.TreeNode{}
root.Right = &tree.TreeNode{5, nil, nil}
root.Right.Left = new(tree.TreeNode)
root.Traverse()
}
目录结构
如何扩充系统类型或者别人的类型
- 定义别名 ```go package main
import “go_code/project04/tree” import “fmt”
type myTreeNode struct { node *tree.TreeNode }
func (myNode *myTreeNode) postOrder() { if myNode == nil || myNode.node == nil{ return }
left := myTreeNode{myNode.node.Left}
left.postOrder()
right := myTreeNode{myNode.node.Right}
right.postOrder()
myNode.node.Print()
}
func main() { var root tree.TreeNode // fmt.Println(root) root = tree.TreeNode{Value: 3} root.Left = &tree.TreeNode{} root.Right = &tree.TreeNode{5, nil, nil} root.Right.Left = new(tree.TreeNode)
root.Traverse()
fmt.Println()
myRoot := myTreeNode{&root}
myRoot.postOrder()
fmt.Println()
}
- 使用组合
```go
package queue
type Queue []int
func (q *Queue) Push(v int) {
*q = append(*q, v)
}
func (q *Queue) Pop() int {
head := (*q)[0]
*q = (*q)[1:]
return head
}
func (q *Queue) IsEmpty() bool {
return len(*q) == 0
}
package main
import (
"go_code/project04/queue"
"fmt"
)
func main() {
q := queue.Queue{1}
q.Push(2)
q.Push(3)
fmt.Println(q.Pop())
fmt.Println(q.Pop())
fmt.Println(q.IsEmpty())
fmt.Println(q.Pop())
fmt.Println(q.IsEmpty())
}
- 使用内嵌 ```go package main
import “go_code/project04/tree” import “fmt”
type myTreeNode struct { *tree.TreeNode //Embedding 内嵌 }
func (myNode *myTreeNode) postOrder() { if myNode == nil || myNode.TreeNode == nil{ return }
left := myTreeNode{myNode.Left}
left.postOrder()
right := myTreeNode{myNode.Right}
right.postOrder()
myNode.Print()
}
func (myNode *myTreeNode) Traverse() { fmt.Println(“this method is shadowed “) }
func main() { // var root tree.TreeNode // fmt.Println(root) root := myTreeNode{&tree.TreeNode{Value: 3}} root.Left = &tree.TreeNode{} root.Right = &tree.TreeNode{5, nil, nil} root.Right.Left = new(tree.TreeNode)
root.Traverse()
fmt.Println()
root.TreeNode.Traverse()
fmt.Println()
root.postOrder()
fmt.Println()
// myRoot := myTreeNode{&root}
// myRoot.postOrder()
// fmt.Println()
} ```