GO基礎3

來源:互聯網
上載者:User

標籤:

// https://tour.golang.org

// 指標,結構體,數組, 切片等

 

 

package main

//  模組匯入 import (  "fmt"  )

// 指標 func show_pointer(){  var p *int  i ,j := 41, 99*37  p = &i  fmt.Println(*p)  *p = 90  fmt.Println(*p)

 p = &j  fmt.Println(*p)  *p = *p / 37  fmt.Println(*p)

}

 

//  結構體

type Vector3 struct {  X int  Y int  Z float64 }

func show_struct(){

 fmt.Println(Vector3{1, 2, 33.456})  v2 := Vector3{9, 88, 77.66}  fmt.Println("=====v2.x=",v2.X)  v2.Y = 66  fmt.Println(v2) }

//  通過指標來訪問結構體

func access_struct_through_pointer() {

 v := Vector3{1, 2, 3}  p := &v  (*p).X = 4  p.Y = 7  fmt.Println(v)  }

 

func show_struct2(){

 v1 := Vector3{1, 2, 3}  v2 := Vector3{X:5}  v3 := Vector3{}  p := &Vector3{5,6,7.7}   fmt.Println(v1, v2, v3, p) }

 

// 數組,類C, 切片類python

func show_array(){  var a [2]string  a[0] = "Hello"  a[1] = "World"  fmt.Println(a)  nums_ori := [6]int{1, 2, 3, 4, 5, 6}  fmt.Println("===origin", nums_ori)

 

 // 切片,類python,但是沒有index < 0的情況,如python中a的最後一個元素可以是a[-1]  nums_sliced := nums_ori[0:4]  fmt.Println("===sliced====", nums_sliced)  //  修改切片的值,切片是原來數組的引用,修改切片的值會影響到原數組的值,用的時候要小心  nums_sliced[0] = 99  fmt.Println("===modified sliced==", nums_sliced)  fmt.Println(nums_ori) }

//  空切片

func show_nil_slice(){

 var s []int  fmt.Println(s, len(s), cap(s))  if s == nil {   fmt.Println("s is nil")  } }

// 內建函數產生切片,修改len,cap

func create_a_slice_with_make(){

 a := make([]int, 5)  //len(a)=5  fmt.Println(a)  b := make([]int, 0, 8) //len(a)=0,cap(a)=8  // 擴充切片,增加len,  b = b[:cap(b)] // cap(b)=8, len(b)=8  //  丟棄掉第一個元素  b = b[1:]   // cap(b)=7, len(b)=7 }

//  append to a slice

func append_to_a_slice(){

 var a [] int  print_slice(a)  a = append(a, 0)  print_slice(a)  a = append(a, 3)  print_slice(a)

}

func print_slice(s []int){  fmt.Printf("lenght=%d,zone_id =%d s=%v\n", len(s), cap(s), s) }

 

// RPC架構GRPC,開源,通用的GRPC架構, 面向移動和HTT2 。 // GRPC基於HTTP/2標準設計,帶來雙向流,流控,頭部壓縮,但TCP串連上的多重複用請求 // 這些特性使得其在行動裝置上表現更好,更省點和節省空間的

func main(){

 // show_pointer()

 // show_struct()

 // access_struct_through_pointer()

 // show_struct2()  

// show_array()

 // show_nil_slice()  append_to_a_slice() }

GO基礎3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.