1. 程式人生 > >Go學習筆記(八)範圍(Range),Map(集合),遞迴函式,型別轉換

Go學習筆記(八)範圍(Range),Map(集合),遞迴函式,型別轉換

Range

range 關鍵字用於for迴圈中迭代陣列(array)、切片(slice)、連結串列(channel)或集合(map)的元素。在陣列和切片中它返回元素的索引值,在集合中返回 key-value 對的 key 值。

package main
import "fmt"
func main() {
    //這是我們使用range去求一個slice的和。使用陣列跟這個很類似
    nums := []int{2, 3, 4}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:"
, sum) //在陣列上使用range將傳入index和值兩個變數。上面那個例子我們不需要使用該元素的序號,所以我們使用空白符"_"省略了。有時侯我們確實需要知道它的索引。 for i, num := range nums { if num == 3 { fmt.Println("index:", i) } } //range也可以用在map的鍵值對上。 kvs := map[string]string{"a": "apple", "b": "banana"} for k, v := range kvs { fmt.Printf("%s -> %sn"
, k, v) } //range也可以用來列舉Unicode字串。第一個引數是字元的索引,第二個是字元(Unicode的值)本身。 for i, c := range "go" { fmt.Println(i, c) } }

執行結果

sum: 9
index: 1
a -> apple
b -> banana
0 103
1 111

Map 集合

Map 是一種無序的鍵值對的集合。Map 最重要的一點是通過 key 來快速檢索資料,key 類似於索引,指向資料的值。

Map 是一種集合,所以我們可以像迭代陣列和切片那樣迭代它。不過,Map 是無序的,我們無法決定它的返回順序。

package main

import "fmt"

func main() {
   var countryCapitalMap map[string]string
   /* 建立集合 */
   countryCapitalMap = make(map[string]string)

   /* map 插入 key-value 對,各個國家對應的首都 */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"

   /* 使用 key 輸出 map 值 */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }

   /* 檢視元素在集合中是否存在 */
   captial, ok := countryCapitalMap["United States"]
   /* 如果 ok 是 true, 則存在,否則不存在 */
   if(ok){
      fmt.Println("Capital of United States is", captial)  
   }else {
      fmt.Println("Capital of United States is not present") 
   }

      /* 根據key*刪除元素  */
   delete(countryCapitalMap,"France");
   fmt.Println("Entry for France is deleted")  
     fmt.Println("刪除元素後 map")   

   /* 列印 map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }

}

執行結果:

Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Capital of United States is not present  

Entry for France is deleted
刪除元素後 map
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi

遞迴函式

遞迴,就是在執行過程中自己呼叫自己。

  • 階乘
package main

import "fmt"

func Factorial(x int) (result int) {
  if x == 0 {
    result = 1; 
  } else {
    result = x * Factorial(x - 1);
  }
  return;
}

func main() {  
    var i int = 15
    fmt.Printf("%d 的階乘是 %dn", i, Factorial(i))
}
  // 結果:15 的階乘是 1307674368000
  • 斐波那契數列
package main

import "fmt"

func fibonaci(n int) int {
  if n < 2 {
    return n
   }
   return fibonaci(n-2) + fibonaci(n-1)
 }

 func main() {
     var i int
     for i = 0; i < 10; i++ {
        fmt.Printf("%dt", fibonaci(i))
     }
 }
 //結果:0 1   1   2   3   5   8   13  21 

型別轉換

型別轉換用於將一種資料型別的變數轉換為另外一種型別的變數

 //中將整型轉化為浮點型,並計算結果,將結果賦值給浮點型變數
 package main

import "fmt"

func main() {
   var sum int = 17
   var count int = 5
   var mean float32

   mean = float32(sum)/float32(count)
   fmt.Printf("mean 的值為: %fn",mean)
}

//輸出結果:mean 的值為: 3.400000