您好,登錄后才能下訂單哦!
這章主要描述如何定義變量、常量、go內(nèi)置類型及go程序設(shè)計(jì)中的一些技巧
go中定義變量的方式很多:
常量就是確定的值,無法改變。(可以是布爾值、可以是字符串、數(shù)值等類型)
語法如下:
const name type = value
go語言中三種內(nèi)置文本類型:string、(字節(jié))byte、(符文)rune
map類型類似于python中字典。實(shí)際就是鍵值對的集合。語法格式如下:
聲明變量,默認(rèn)map是nil,nil map不能直接賦值,默認(rèn)是0
var map_variable_name map[key_data_type]value_data_type
使用make函數(shù)創(chuàng)建一個(gè)非nil的map,因?yàn)閚il map不能存放鍵值對。
map_variable_name = make(map[key_data_type]value_data_type,cap)
簡潔的:map_variable_name := map[key_data_type]value_data_type{k1:v1,k2:v2,….}
以下是兩種定義例子
上面的cap可以省略,但是在用時(shí)最好合理設(shè)置,為什么?
如果里面的key-value鍵值對超出容量,則容量會(huì)自動(dòng)擴(kuò)容(因?yàn)槊恳淮蔚臄U(kuò)容都是重新分配內(nèi)存和拷貝)
map中的key是獨(dú)一無二的。
使用len()可以獲得元素個(gè)數(shù)
使用delete()可以操作鍵值對的刪除
delete(key,value) //注意不能是nil map,否則會(huì)拋出異常panic。
使用for….range對map進(jìn)行迭代操作。
map的讀取和設(shè)置類似于slice,通過key來進(jìn)行操作,但是又有所不同,map中key可以是int、string、float(最好不用float)(只要是支持==或者!=類型的都可以,這里函數(shù)、map、slice不支持),而slice中的索引只能是int類型。value可以是其他任意類型。
map查找比線性搜索快,但是比使用索引訪問數(shù)據(jù)的類型慢很多(據(jù)說慢100倍)。
注意:
1)map中的元素不是變量,因此不能尋址。具體原因是:map可能會(huì)隨著元素的增多重新分配更大的內(nèi)存空間,舊值都會(huì)拷貝到新的內(nèi)存空間,因此之前的地址就會(huì)失效。
2)map中使用for…range遍歷,(也就是說不能使用索引的方式獲取鍵值,但是可以重新賦值)同時(shí)它的迭代順序是不確定的,也就是說每執(zhí)行一次結(jié)果的順序都可能不同。在go語言中是有意的這么設(shè)計(jì),是為例避免程序依賴于某種哈希實(shí)現(xiàn),目的是為了程序的健壯。如果非要按順序遍歷,必須顯示對key排序,可以使用sort包中的String函數(shù)。代碼如下,一般最好不要這樣使用。
import “sort”
var names []string
for ,name := range ages {
names = append(names, name)
}
sort.Strings(names)
for , name := range names {
fmt.Printf("%s\t%d\n", name, ages[name])
}
map中如果沒有該key則返回值為0,但是如果該key存在且鍵值是0,如何判斷?
map功能的查找:
value, ok := map[“1”]
if ok{
//處理查到的value值
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。