go語言小知識

2021-09-25 12:41:02 字數 1483 閱讀 4453

1、陣列越界

numbers:=string

//cleaned := make(string,0)

cleaned:=string{} // empty slice

fmt.println("before:",len(cleaned))

counter:=0

for _, str := range numbers

cleaned[counter]=str // panic

counter++

}

修復

numbers:=string

//cleaned := make(string,0) // 2種寫法都可以

cleaned:=string{} // empty slice

counter:=0

for _, str := range numbers

counter++

}

2、 閉包捕獲環境

for i,v := range string()

}time.sleep(10*time.second)

// 列印結果

the programming language at index 3 is v

the programming language at index 3 is v

the programming language at index 3 is v

the programming language at index 3 is v

修復

for i,v := range string(i,v)

}time.sleep(10*time.second)

// 列印結果 (每次執行結果不一樣)

the programming language at index 2 is rust

the programming language at index 0 is c

the programming language at index 3 is v

the programming language at index 1 is go

3、 事務

更新單張表不需要加事務,即便是加,也得保證開啟事務,回滾/提交是成對出現的。

慎用事務。

4、 for range

type person struct 

type personbyname person

func (p personbyname)len() int

func (p personbyname) less(i,j int) bool

sort.sort(personbyname(v))

}

有關for range使用的注意事項可以參考文章golang中range的使用方法及注意事項。

Go語言小程式

1 演示全域性變數的使用 2 init函式先於main函式執行 package main import fmt varname string 宣告全域性變數 func main func init 執行結果 howard good morning 1 用關鍵字var宣告變數,格式 var 變數名變數...

go語言相關知識

1 在我們以前熟悉的各種語言中都有這樣幾個概念 系統路徑,官方包路徑,第三方包路徑,專案路徑。好了go中只有兩個路徑.問題 專案路徑和第三方包路徑呢?首先 go中是沒有專案這個概念的,只有包。可執行包只是特殊的一種,類似我們常說的專案 gopath可以設定多個,不管是可執行包,還是非可執行包,通通都...

GO語言基本知識

go語言中,變數的宣告與pascal類似 var name int 先用var表示這是乙個變數,然後緊跟變數名,最後是變數型別。與c 一樣,存在指標型別,用 來取位址。數字型別,包括整數與浮點數。常用的用int32,int64,float32,float64。此外還有複數型別 complex64 注...