Back

go - 从ruby 到go go 快速入门

发布时间: 2021-09-05 08:45:00

array

数组,从声明开始,长度就是固定的。

slice

切片, 长度可以变化的数组( 声明的时候就不带长度)

var my_slice []int

my_slice = make( []int, 3 , 5)    3 : cap   5 : 长度,   [0, 0 ,0 ] (被初始化了)

my_slice2 := []int { 1,2,3}   ,  则:   cap(my_slice2) = 3,  len(my_slice2) = 3

操作: 可以截取:  

my_slice2[0:2]   =>  { 1, 2, 3}

my_slice2[0:]    从0 开始返回所有

my_slice2[:1]  从0 开始返回到index 1

copy:   copy(to_slice, from_slice)   

append(my_slice, 70)  把 70 放到 my_slice 最后一个

map

也叫哈希

make 是关键字,用来给 array, slice, map 做初始化. 设置 cap 和len. 

cap: 占用的多少内容

len: 长度

for:
做循环
使用range 来打印slice , 等。 例如   for  index, value := range my_slice { fmt.Println(index, value )}
两个运算符号:  &,  * 
var a int = 10     
&a      a的地址   , 0xc00001a140
var pointer *int
pointer = &a       // pointer:  0xc00001a140
非常好的例子:https://www.runoob.com/go/go-function-call-by-reference.html
调用函数:
swap(&a, &b)
声明函数:
func swap(a *int, b *int) {
    temp := *a
    *b = *a
    *a = temp
}
在上面函数体重:
*a : 获取  指针 a 对应的内容
&a : 获取 变量a  的地址
var a *int   则是对变量进行声明,    (a *int) 表示a 是一个pointer参数

声明strut和方法

type Fruit struct {

  name string
  color string
  status string
}

func eat( fruit *Fruit) {
  fruit.status = "eaten"
  fmt.Println("fruit is eaten: ", fruit)
}

func (f *Fruit) bite(times int) {
  fmt.Println("you bite ",  times, " times of this fruit" , f)
}

func main (){ 

  var apple = Fruit{ name: "apple", color: "red"}
  fmt.Println(apple)

  eat(&apple)
  fmt.Println(apple)

  apple.bite(3)
}
输出:

{apple red }
fruit is eaten: &{apple red eaten}
{apple red eaten}
you bite 3 times of this fruit &{apple red eaten}

字符串的split :

func minWindow(s string, t string) string {

  s2 := "hello, banana!"
  for index, element := range s2 {
    fmt.Printf("== index %d, element %c \n", index, element)
    fmt.Println(string(element))
  }
  return ""
}


结果如下:


== index 0, element h 
h
== index 1, element e 
e
== index 2, element l 
l
== index 3, element l 
l
== index 4, element o 
o
....

查看某个变量的类型

fmt.Printf(" var is %T", var)

import "reflect"

reflect.TypeOf(var)   // => 也能打印类型出来

Back