GO基础3

// 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 ", 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() }

原文地址:https://www.cnblogs.com/Wolfanature/p/5837792.html