Go 基本語法(方便查詢,不斷完善中。。。)

一、tips

1、main函數只有在main包中纔可以跑起來

2、package名字是隨便起的,不一定非要有個實體的文件夾

3、一個較爲複雜的傻瓜for循環 :)

for i, j := 0, len(stringValue)-1; i <= j; i, j = i+1, j-1 {
   if stringValue[i] != stringValue[j] {
      return false
   }
}

二、struct

1、結構體初始化

type Rect struct {

    x, y float64

    width, height float64

}

rect1 := new (Rect)

rect2 := &Rect{}

rect3 := &Rect{0, 0, 100, 300}

rect1 := &Rect{width=100, height =300}

2、定義結構體方法

type ListNode struct {
   Val  int
   Next *ListNode
}

//自定義打印鏈表方法
func (temp *ListNode) myPrint() {
   for temp != nil {
      fmt.Print(strconv.Itoa(temp.Val) + "->")
      temp = temp.Next
   }
}

調用方法:

node1.myPrint()

三、字符串

1、String int相互轉換

string轉成int: 
int, err := strconv.Atoi(string)
string轉成int64: 
int64, err := strconv.ParseInt(string, 10, 64)
int轉成string: 
string := strconv.Itoa(int)
int64轉成string: 
string := strconv.FormatInt(int64,10)

2、求字符串長度

len(stringValue)
 

四、數組

1、切片數組定義&初始化:

result := make([]int, 2) //裏面有2個元素,爲0

nums := []int{1,3,5,6}

2、切片數組填充元素:

result[0] = index

n、常見錯誤

 

五、map

1、map定義:

var tempMap map[int] int

2、map定義&初始化:

var tempMap := make(map[int]int)

3、map填充元素:

tempMap[index] = value

3、map查找元素:

value, ok := tempMap[index]
if ok {

}

n、常見錯誤

var tempMap map[int] int
for index, value := range nums {
   tempMap[value] = index
}

但是這樣執行會報錯:panic: assignment to entry in nil map

原因是:map必須初始化後才能使用,要改成如下

tempMap := make(map[int]int)
for index, value := range nums {
   tempMap[value] = index
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章