go_封装

go语言中首字母大写表示public

go语言中首字母小写表示private

结构定义的方法必须放在同一个包内

一个目录只能放一个包

 

如何扩充系统的类型或别人的类型:

 

1.定义别名

 

2.使用组合

 

使用组合

 

目录结构:

 

入口:entry.go

package main

import (
	"learngo/tree"
)

func main() {
	var root tree.Node
	//fmt.Println(root)
	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)
	//fmt.Println(root)

	root.Traverse()
	//nodes :=[]TreeNode{
	//	{value:5},
	//	{},
	//	{6,nil,&root},
	//}
	//fmt.Println(nodes)

	//root.print()
	//root.right.left.setValue(8)
	//root.right.left.print()
	//fmt.Println()
	//
	//root.print()
	//root.setValue(100)
	//root.print()
	//
	//var  pRoot *TreeNode
	//pRoot.setValue(120)
	//pRoot =&root
	//pRoot.setValue(220)
	//pRoot.print()
	//root.print()


}

  函数体:node.go

package tree

import "fmt"

//结构体,相当于对象,实体
type Node struct {
	Value int
	Left,Right * Node
}

//(node TreeNode)相当于其他语言的this,表示print()是给node接收的
func (node Node) Print(){
	fmt.Print(node.Value," ")
}

func (node *Node) SetValue(value int){
	if node == nil{
		fmt.Println("Setting nil value")
		return
	}
	node.Value = value
}

//使用工厂函数来构造结构体
func CreateNode(value int) *Node{
	return &Node{Value:value}
}

定义别名

函数体:queue.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
}

入口:entry.go

package main

import (
	"learngo/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())

}

  

posted @ 2018-03-12 18:05  小白兔奶糖  阅读(179)  评论(0编辑  收藏  举报