Go學習筆記(二)

  1. 定義結構體:

        type struct_variable_type struct {
       member definition;
       member definition;
       ...
       member definition;
    }
  2. 結構體example:

    // struct_test2.go
    
    package main
    
    import (
        "fmt"
    )
    
    type Book struct {
        author  string
        title   string
        book_id int
        subject string
    }
    
    func main() {
        var book1 Book
        book1.author = "lryong1"
        book1.title = "test1"
        book1.subject = "wulala"
        book1.book_id = 1
    
        var book2 Book
        book2.author = "lryong2"
        book2.title = "test2"
        book2.subject = "wakaka"
        book2.book_id = 2
    
        gen_inform(&book1) //傳遞book1結構體的地址
        gen_inform(&book2)
    
    }
    
    func gen_inform(*a Book) { //結構體指針
        fmt.Printf("Book's title is %s\n", a.title)
        fmt.Printf("Book's author is %s\n", a.author)
        fmt.Printf("Book's book_id is %d\n", a.book_id)
        fmt.Printf("Book's subject is %s\n", a.subject)
        fmt.Printf("Book's information is %d\n", a.try_method())
        fmt.Println("============================")
    }
    
    func (a Book) try_method() int {
        return a.book_id << 4
    }
  3. Golang的雙引號和反引號,單引號:

    • 雙引號和反引號都用於表示一個常量字符串。
    • 雙引號用來創建可解析的字符串字面量(支持轉義,但不能用來引用多行)。
    • 反引號用來創建原生的字符串字面量,這些字符串可能由多行組成(不支持任何轉義序列),原生的字符串字面量多用於書寫多行消息、HTML以及正則表達式。
    • 而單引號則用於表示Golang的一個特殊類型:rune,類似其他語言的byte但又不完全一樣,是指:碼點字面量(Unicode code point),不做任何轉義的原始內容。
  4. Go 數組的長度不可改變,在特定場景中這樣的集合就不太適用,Go中提供了一種靈活,功能強悍的內置類型切片(“動態數組”),與數組相比切片的長度是不固定的,可以追加元素,在追加時可能使切片的容量增大。
  5. Go 語言中 range 關鍵字用於for循環中迭代數組(array)、切片(slice)、通道(channel)或集合(map)的元素。在數組和切片中它返回元素的索引值,在集合中返回 key-value 對的 key 值。example:

    // range_test1.go
    package main
    
    import (
        "fmt"
    )
    
    func main() {
        //使用range求一個slice的和,跟使用數組相似
        var test = []int{2, 4, 6}
        sum := 0
    
        for _, num := range test { //"_"只是可寫變量,省略索引
            sum += num
        }
    
        fmt.Println("sum result is ", sum)
    
        for i, v := range test {
            if v == 6 {
                fmt.Println("index:", i)
            }
        }
        //range也可以用在map的鍵值對上。
        kvs := map[string]string{"a": "apple", "b": `banana`}
        for k, v := range kvs {
            fmt.Printf("%s -> %s\n", k, v)
        }
        //range也可以用來枚舉Unicode字符串。第一個參數是字符的索引,第二個是字符(Unicode的值)本身
        for i, c := range "go" {
            fmt.Printf("%d -> %d\n", i, c)
        }
    
    }
  6. Go語言Map(集合):Map 是一種集合,所以我們可以像迭代數組和切片那樣迭代它。不過,Map 是無序的,我們無法決定它的返回順序,這是因爲 Map 是使用 hash 表來實現的。定義方式:

        /* 聲明變量,默認 map 是 nil */
    var map_variable map[key_data_type]value_data_type
    
    /* 使用 make 函數 */
    map_variable = make(map[key_data_type]value_data_type)
    • example:
          // map_test1.go
      package main
      
      import (
          "fmt"
      )
      
      func main() {
          // var countryCapitalMap map[string]string //gen map,無序
          countryCapitalMap := make(map[string]string)
      
          countryCapitalMap["France"] = "Paris"
          countryCapitalMap["Italy"] = "Rome"
          countryCapitalMap["Japan"] = "Tokyo"
          countryCapitalMap["India"] = "New Delhi"
          countryCapitalMap["United States"] = "New York"
      
          for country := range countryCapitalMap {
              fmt.Printf("The capital of %s is %s\n", country, countryCapitalMap[country])
          }
      
          capital, ok := countryCapitalMap["United States"] //查看元素在集合中是否存在
          if ok {
              fmt.Println("Capital of United States is ", capital, "!!!")
          } else {
              fmt.Println("Capital of United States is not present.")
          }
      
          delete(countryCapitalMap, "United States")
          fmt.Println("United States has been deleted.")
      }
  7. 接口:Go 語言提供了另外一種數據類型即接口,它把所有的具有共性的方法定義在一起,任何其他類型只要實現了這些方法就是實現了這個接口。

    • example:
      // interface_example1.go
      package main
      
      import (
          "fmt"
      )
      
      type Phone interface {
          call()
      }
      
      type NokiaPhone struct{}
      
      func (phone NokiaPhone) call() {
          fmt.Println("I'm Nokia,I can call you!")
      }
      
      type IPhone struct{}
      
      func (phone IPhone) call() {
          fmt.Println("I'm iphone,I can call you!")
      }
      
      func main() {
          var test_phone Phone
          test_phone = new(NokiaPhone)
          test_phone.call()
      
          test_phone = new(IPhone)
          test_phone.call()
      }
  8. Go 語言通過內置的錯誤接口提供了非常簡單的錯誤處理機制。error類型是一個接口類型.

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