go語言常用操作

2021-10-06 03:18:15 字數 2057 閱讀 9558

package main

import

("fmt"

)func

main()

if

else

ifelse

forgoto

(轉移到被標記的語句)

len 長度 cap 容量

a:=[3

]int

var b [

]int

= a[1:

4][:

] 前閉後開 陣列切片

陣列操作方法:

copy

kay-value型別 

a:=map

[string

]int

inte***ce

空型別map[

inte***ce

]inte***ce

map 操作方法:

delete

nums :=

intsum :=

0for key, value :=

range nums

}

初始化 切片 map等

a:=make([

]int,4

)b:=

make

(map

[string

]float64

,100

)

fmt.

println

(123

)//列印值

fmt.

printf

("%t"

,123

)//列印型別

type books struct

package main

import

("bufio"

"fmt"

"io"

"os"

)func

main()

//寫入

funcxr(

)//及時關閉

defer file.

close()

//寫入內容

str :=

""// \n\r表示換行 txt檔案要看到換行效果要用 \r\n

//寫入時,使用帶快取的 *writer

writer := bufio.

newwriter

(file)

for i :=

0; i <

3; i++

//因為 writer 是帶快取的,因此在呼叫 writerstring 方法時,內容是先寫入快取的

//所以要呼叫 flush方法,將快取的資料真正寫入到檔案中。

writer.

flush()

}//讀取

funcdq(

)//及時關閉 file 控制代碼,否則會有記憶體洩漏 等同於析構函式

defer file.

close()

//建立乙個 *reader , 是帶緩衝的

reader := bufio.

newreader

(file)

for fmt.

print

(str)

} fmt.

println

("檔案讀取結束..."

)}

package main

import

("bufio"

"fmt"

"io"

"os"

)func

main()

func

say(s string

)}

go 常用操作

func struct2map obj inte ce map string inte ce for i 0 i t.numfield i return data 注意 如果報錯 handler crashed with error reflect numfield of non struct ty...

GO 語言常用排序

1.氣泡排序 bubble sort 的基本思想 比較相鄰兩個 元素的關鍵字值,如果反序,則交換 func bubblesort arr int 判斷資料是否是有序 if flag else 2.快速排序 快速排序 quick sort 是一種分割槽交換排序演算法.它的基本思想 在資料序列中選擇乙個...

go語言常用函式

示例1 1 arr1 int 3 fmt.println arr2 輸出 1,2,3,4,5,6 1 arr1 int 2 arr2 int 4 fmt.println arr3 輸出 1,2,3,4,5,6 copy 用於從乙個陣列切片複製到另乙個陣列切片。如果加入的兩個陣列切片不一樣大,就會按其...