Go 提供了另外一種重要的數(shù)據(jù)類型:映射(Map) 窥突,它將唯一鍵映射到值。鍵是用于在檢索值的對(duì)象硫嘶。給定一個(gè)鍵和一個(gè)值就可以在 Map 對(duì)象中設(shè)置值阻问。設(shè)置存儲(chǔ)值后,就可以使用其鍵值索引它對(duì)應(yīng)的值了沦疾。
>教程來自 http://www.yiibai.com/go/go_start.html
感謝博主的精心編寫称近。
定義映射
必須使用 make 函數(shù)來創(chuàng)建映射第队。
//聲明一個(gè)變量,默認(rèn)map是空
var map_variable map[key_data_type]value_data_type
//創(chuàng)建映射
map_variable = make(map[key_data_type]value_data_type)
映射的創(chuàng)建和使用:
func main(){
var contryCapitalMap map[string]string
// create a map
contryCapitalMap = make(map[string]string)
// insert key-value pairs in the map
countryCapitalMap["France"] = "Paris"
countryCapitalMap["Italy" ] = "Rome"
countryCapitalMap["Japan" ] = "Tokyo"
countryCapitalMap["India" ] = "New Delhi"
// print map using key
for country := range countryCapitalMap{
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
// test if entry is present in the map or not
capital , ok := countryCapitalMap["United States"]
if(ok){
fmt.Println("Captial of United States is",capital)
}else{
fmt.Println("NONE")
}
}
delete() 函數(shù)
delete()函數(shù)用于從映射中刪除項(xiàng)目刨秆。它需要映射以及制定要?jiǎng)h除的相應(yīng)鍵凳谦。以下是示例:
func main(){
// create a map
countryCapitapMap := map[string]string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
fmt.Println("Original map")
//print map
for count : range countryCapitalMap{
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
//delete an entry
delete(countryCapitalMap,"France");
for country := range countryCapitalMap{
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
}
}
Go語(yǔ)言遞歸
遞歸是以自相似的方式重復(fù)項(xiàng)的過程。這同樣適用于其它編程語(yǔ)言衡未,在編程語(yǔ)言中允許在函數(shù)內(nèi)調(diào)用同一個(gè)函數(shù)稱為遞歸調(diào)用尸执,如下所示。
func recursion(){
recursion() // function calls itself
}
func main(){
recursion()
}
Go編程語(yǔ)言支持遞歸缓醋,即函數(shù)調(diào)用自身的函數(shù)如失。但是在使用遞歸時(shí),程序員需要注意在函數(shù)中定義或設(shè)置一個(gè)退出條件送粱,否則會(huì)進(jìn)入一個(gè)無限循環(huán)褪贵。
遞歸函數(shù)非常有用,可用于解決許多數(shù)學(xué)問題抗俄,計(jì)算階乘竭鞍,生成斐波那契數(shù)列等。
數(shù)字階乘示例
func factorial(i int)int{
if(i <= 1){
return 1
}
return i * factorial(i - 1)
}
func main(){
var i int = 15
fmt.Printf("Factorial of %d is %d",i,factorial(i))
}
斐波那契系列示例
func fibonaci(i int)(ret int){
if i == 0 {
return 0
}
if i == 1 {
return 1
}
return fibonaci(i-1) + fibonaci(i-2)
}
func main(){
var i int
for i = 0 ; i < 10 ; i++ {
fmt.Printf("%d",fibonaci(i))
}
}
Go 語(yǔ)言類型轉(zhuǎn)換
類型轉(zhuǎn)換是一種將變量從一種數(shù)據(jù)類型轉(zhuǎn)化為另一種數(shù)據(jù)類型的方法橄镜。例如,如果將長(zhǎng)整型值存儲(chǔ)到簡(jiǎn)單的整數(shù)類型冯乘,那么可以將轉(zhuǎn)換 long 類型為 int 類型洽胶。可以使用 轉(zhuǎn)換操作符 將值從一種類型轉(zhuǎn)換為另一種類型裆馒,如下所示:
rype_name(expression)
看看下面的例子姊氓,其中轉(zhuǎn)換操作符將一個(gè)整數(shù)變量并將其結(jié)果值轉(zhuǎn)換為浮點(diǎn)數(shù)。
func main(){
var sum int = 17
var conunt int = 5
var mean float32
mean = float32(sum)/float32(count)
fmt.Printf("Value of mean :%f\n",mean)
}
Go語(yǔ)言接口
Go語(yǔ)言提供了另一種稱為接口 interface 的數(shù)據(jù)類型喷好,它代表一組方法簽名翔横。struct 的數(shù)據(jù)類型實(shí)現(xiàn)這些接口的方法。
語(yǔ)法
//定義一個(gè)數(shù)據(jù)類型
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}
//定義一個(gè)結(jié)構(gòu)
type struct_name struct{
//variable
}
func (struct_name_variable struct_name)method_name1()[return_type]{
//method implementation
}
func (struct_name_variable struct_name)method_name2()[return_type]{
//method implementation
}
示例
type Sharp interface{
area() float64
}
type Circle struct{
x,y,radius float64
}
type Rectangle struct{
width,height float64
}
func(circle Circle) area() float64{
return math.Pi * circle.radius * circle.radius
}
func(rect Rectangle) area() float64{
return rect.width * rect.height
}
func getArea(shape Shape) float64{
return shape.area()
}
func main(){
circle := Circle{x:0,y:0,radius:5}
rectangle := Rectangle{width:10,height:5}
fmt.Println(getArea(circle))
fmt.Println(getArea(rectangle))
}
Go語(yǔ)言錯(cuò)誤處理
Go編程提供了一個(gè)非常簡(jiǎn)單的錯(cuò)誤處理框架梗搅,以及內(nèi)置的錯(cuò)誤接口類型禾唁,如下聲明:
type error interface {
Error() string
}
函數(shù)通常返回錯(cuò)誤作為最后一個(gè)返回值∥耷校可使用 errors.New 來構(gòu)造一個(gè)基本的錯(cuò)誤消息荡短,如下圖所示:
func Sqrt(value float64)(float64, error){
if(value < 0){
return 0 , errors.New("Math: negative number passed to Sqrt")
}
return math.Sqrt(value)
}
使用返回值和錯(cuò)誤信息,如下圖所示:
reslut , error := sqrt(-1)
if err != nil {
fmt.Println(err)
}