1. 程式人生 > 實用技巧 >go 隨便學習筆記

go 隨便學習筆記

go的學習筆記
# new 和make 的區別
new - 用於分配記憶體 , 返回指標。 分配的空間被清零。 建立map時需要進行初始化才能使用。
make - 只能用於 slice 、map 、channel 的初始化 ,返回指標指向的值。 進行初始化。

func main(){
countryCapitalMapBynew := new(map[string]string)
*countryCapitalMapBynew = map[string]string{"France": "巴黎"}
/* map插入key - value對,各個國家對應的首都 */ 
(*countryCapitalMapBynew)["
American"] = "華盛頓" var countryCapitalMap map[string]string /*建立集合 */ countryCapitalMap = make(map[string]string) countryCapitalMap["Italy"] = "羅馬" }

# 擴充套件函式的定義

type tree struct {
v int
l *tree
r *tree
}

func (t *tree) Sum() int {

if t == nil {
return 0
}
return t.v + t.l.Sum() + t.r.Sum()
}
treeList :
= &tree{ init } 使用 treeList.Sum()

# Slice 切片 表示陣列的抽象。 包含三部分 ptr ,len ,cap
make([]T, length, capacity) /*capacity 為可選引數*/
可以通過len() 獲取切片長度
可以通過cap() 可以測量最長可以達到多少
append() 在slice 尾部新增元素
copy(slice1 ,slice2) 函式將slice2拷貝到slice1 但是不會超出slice1 定義的長度。例如

func main() {
arr1 := make([]int, 10)
arr1 = []int
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} printSlice(arr1) slice2 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} printSlice(slice2) slice2 = append(slice2, 1, 2, 3, 45, 6, 7) printSlice(slice2) copy(arr1, slice2) printSlice(arr1) } func printSlice(x []int) { fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x) }

# 關於切片 對陣列進行切片操作之後再append操作 。 切片的cap 為 arrcap+append.count ,使用切片表示式當設定的值大於len小於cap 多出來的值會以預設形式補齊(例如 int 為0)。示例程式碼

func main() {
    a := [5]int{1, 2, 3, 4, 5}
    fmt.Printf("s:%v len(s):%v cap(s):%v\n", a, len(a), cap(a))
    // a = append(a, 1)
    s := a[:3] // s := a[low:high]
    fmt.Printf("before: s:%v len(s):%v cap(s):%v\n", s, len(s), cap(s))
    s = append(s, 0, 1, 2, 3, 4, 5, 6, 7)
    fmt.Printf("end: s:%v len(s):%v cap(s):%v\n", s, len(s), cap(s))
    // fmt.Printf("&s:%v \n", &s)
    s2 := s[:12] // 索引的上限是cap(s)而不是len(s)
    fmt.Printf("s2:%v len(s2):%v cap(s2):%v\n", s2, len(s2), cap(s2))
}


# 全域性變數可以和區域性變數重名。作用域內優先使用區域性變數。
# 關於range 關鍵字 。類似 c# foreach 。常用語迴圈 array 、slice 、channel、map。