容器

Go学习笔记

数组

切片(Slice)

1、扩展
arry := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println("arry = ", arry)
s1 = arry[2:6]
s2 = s1[3:5]

image-20190825165300639

Slice可以向后扩展,不可以向前扩展

s[i]不可以超越len(s),向后扩展不可以超越底层数组cap(s)

添加元素时,如果超越cap,系统会重新分配更大的底层数组

由于值传递的关系,必须接收append的返回值。如:s = append(s, val)

Slice实现原理

image-20190825174041113

Map

Map创建:make(map[string]int)

获取元素:m[key]

key不存在时,获取Value类型的初始值

使用value, ok := m[key]来判断是否存在key

使用delete函数删除一个key

使用range遍历key,或者key/value对

不保证遍历顺序,如需要顺序,需手动对key进行排序

使用len函数获取元素个数

map的key适用类型

  • map使用哈希表,必须可以相等比较
  • 除了slice, map, function的内建类型都可以作为key
  • Struct类型不包含上述字段,也可以作为key

程序结构

Go学习笔记

条件语句 1、if…else… 条件内可以赋值 条件内赋值的变量作用域就存在于这个if语句里 if contents, err := ioutil.ReadFile(filename); err == nil { fmt.Println(string(contents)) } else { fmt.Println("cannot print file contents: ", err) } 2、switch switch后可以没有表达式 不需要显示break,switch会自动break,除非使用fallthrough func grade(score int) string { g := "" switch { case score < 0 || score > 100: panic(fmt.Sprintf("Wrong score: %d", score)) case score < 60: g = "F" case score < 80: g = "C" case score < 90: g = "B" case score <= 100: g = "A" } return g } 3、for 表达式不需要括号 [Read More]
Go 

Go 变量

Go学习笔记

变量定义 1、使用var关键字(变量类型写在变量名之后) var a, b, c bool var s1, s2 string = “hello”, “world” 可定义在函数体内或直接定义在包内 使用var()集中定义变量 var ( a, b, c) 2、编译器自动识别类型 var a, b, i, s1, s2 = true, false, 1, “hello”, “world” 3、使用:=定义 a, b, i, s1, s2 := true, false, 1, “hello”, “world” 只能在函数体内定义使用 命名规则:一个名字必须以一个字母(Unicode字母)或下划线开头,后面可以跟任意 数量的字母、数字或下划线。大写字母和小写字母是不同的。关键字不能用于自定义名字,只能在特定语法结构中使用。 Go语言中不存在 未初始化的变量 类型必须完全匹配,nil可以赋值给任何指针或引用类型的变量 25个关键字 break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var 内建常量 true, false, iota, nil 内建变量类型 1、bool, string 2、(u)int, (u)int8, (u)int16, (u)int32, (u)int64, uintptr(指针) 3、byte, rune(字符) 4、float32, float64, complex64, complex128 5、error 内建函数 1、make, len, cap, new, append, copy, close, delete 2、complex, real, imag 3、panic, recover 强制类型转换 类型转换是强制的 var a, b int = 3, 4 var c int = int(math. [Read More]
Go 

GO 概述

Go学习笔记

区别于其它语言

  • 没有" 对象",没有继承、多态,没有泛型,没有try/catch
  • 有接口,函数式编程,CSP并发模型(goroutioe + channel)
Go