大家好,又見面了,我是全棧君。
一.結構體和方法
面向對象
- go語言僅支援封裝,不支援繼承和多态
- go語言沒有class,隻有struct結構體
結構的建立
- 不論位址還是結構本身,一律使用.(點)來通路成員
- 使用自定義工廠函數
- 注意傳回了局部變量的位址
- go語言沒有構造函數
結建構立在堆上?棧上: 不需要知道 垃圾回收
使用指針作為方法接受者
- 隻有使用指針才可以改變結構内容
- nil指針也可以調用方法
值接受者vs指針接受者
- 要改變内容必須使用指針接受者
- 結構過大也考慮使用指針接受者
- 一緻性:如有指針接受者,做好都是指針接受者(建議)
- 值接受者是go語言特有,指針接受者其他語言都有
- 值/指針接受者均可接受值/指針
package main
import "fmt"
type treeNode struct {
value int
left, right *treeNode //指針
}
//自定義工廠函數
func createNode(value int) *treeNode {
return &treeNode{value: value} //傳回局部變量的位址
}
/**
go語言所有參數傳值
為結構定義方法
顯示定義和命名方法接受者
*/
//值接受
func (node treeNode) print() {
fmt.Print(node.value," ")
}
//指針接受
func (node *treeNode) setValue(value int) {
if node==nil {
fmt.Println("setting value to nil node ")
return
}
node.value = value
}
//子樹周遊
//中式周遊:先左再中再右
func (node *treeNode)traverse() {
if node==nil {
return
}
node.left.traverse()
node.print()
node.right.traverse()
}
func main() {
var root treeNode
root = treeNode{value: 3}
root.left = &treeNode{} //左子樹 取位址
root.right = &treeNode{5, nil, nil} //右子樹
root.right.left = new(treeNode)
//fmt.Println(root)
root.left.right = createNode(2)
root.right.left.setValue(4)
root.right.left.print()
fmt.Println()
//root.print()
//root.setValue(100)
//
//var pRoot *treeNode
//pRoot.setValue(200)
//pRoot=&root
//pRoot.setValue(300)
//pRoot.print()
fmt.Println()
root.traverse()//0 2 3 4 5
//pRoot:=&root
//pRoot.print()
//pRoot.setValue(200)
//pRoot.print()
/*nodes:=[]treeNode{
{value:3},
{},
{6,nil,&root},
}
fmt.Println(nodes)*/
}
複制
二,包和封裝
針對包來說
- 名字一般使用CamelCase
- 首字母大寫:public 公有
- 首字母小寫:private 私有
包:
- 每個目錄一個包
- main包包含可執行入口(main 函數)
- 為結構定義的方法必須放在同一個包内
- 可以是不同的檔案
package main
import "fmt"
func main() {
//one:=0
one,two:=1,2
one,two=two,one //交換變量值
fmt.Println(one,two)
}
複制
如何擴充系統類型或者别人的類型
- 定義别名
- 使用組合
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
}
複制
mian.go 檔案
package main
import (
"../../queue"
"fmt"
)
func main() {
q := queue.Queue{1} //隊列先進先出
q.Push(2)
q.Push(3)
fmt.Println(q.Pop()) //1
fmt.Println(q.Pop()) //2
fmt.Println(q.IsEmpty()) //false
fmt.Println(q.Pop()) //3
fmt.Println(q.IsEmpty()) //true
}
複制
四.gopath環境變量
- 預設在~/go(unix,linux),%userprofile%\go(windows):
- 例如GOROOT=/usr/local/go #gosetup GOPATH=/Users/liutao/go #gosetup
- 官方推薦:所有項目和第三方庫都放在同一個gopath下
- 也可以将每個項目放在不同的gopath
釋出者:全棧程式員棧長,轉載請注明出處:https://javaforall.cn/111719.html原文連結:https://javaforall.cn