golang 中常见的内置类型
golang 中常用的几种内置类型如下
- string
- Slice
- Channel
- map
- Interface {}
string
golang 中的 string 为值类型,与 python 的 str 大致相同,赋值后无法再修改 string 中的内容,但可以通过方法函数构造新的 string
Slice
在 golang 中的数组类型是值类型,传参时会复制整个数组,但是 Slice 是对底层数组的一段内容的引用。
1 | data := [...] int {1, 2, 3, 4 ,5 ,6 ,7} |
data[1:4:5] 中三个参数分别代表 data 中的 low, high, max
得到的 slice 的即为 {2, 3, 4}, 它的
Channel
channel 用来在多个 rountine 之间无阻塞的发送消息
1 | ch := make(chan int, 10) |
make 的第二参数为该 channel 的长度,如果为 0, 那么这个 channel 就不带 buffer, 如果
如果 channel 不带 buffer, 那么传送数据不会发生拷贝,读在写之前发生
如果 channel 带 buffer,那么传送数据就会发生拷贝,写在读之前发生
当 channel 为空时,读取操作会阻塞。
写入一个 closed 的 channel 会导致 panic
channel 支持三个操作
read
1
v := <- ch
write
1
ch <- v
close
1
close(ch)
channel 是并发安全的
map
1 | // nil map, can't use |
map 实现了键值表,能够实现
map 支持如下几种操作
insert or upadte
1
m[key] = element
retrieve an element
1
ele = m[key]
delete
1
delete(m, key)
test key
1
ele, ok := m[key]
Interface
抽象类型,没有具体值,唯一确定的是他包含某种方法
1 | type geometry interface { |
在 golang 中实现该接口,只需要在定义类型时实现该接口中的同名方法即可。
1 | type rect struct { |