Go语言中没有_len函数,只有len(获取字符串、切片、数组、map和channel的长度)、cap(获取切片、数组指针和channel的容量)和append(向切片追加元素并可能扩容)。
Go 语言中没有 _len 这个内置函数,你可能是指 len(注意没有下划线)。Go 的内置函数包括 len、cap、append、make、copy、delete、panic、recover 等,其中 len 和 cap 用于获取长度和容量,append 用于向切片追加元素。
len 返回字符串、切片(slice)、数组(array)或 map 的元素个数。对通道(channel)也适用,返回当前队列中未被接收的元素数。
len("你好") 返回 4(按字节计,UTF-8 编码下“你”“好”各占 3 字节)s := []int{1,2,3}; len(s) 返回 3
a := [5]int{1,2}; len(a) 返回 5(数组长度固定,是类型的一部分)m := map[string]int{"a":1,"b":2}; len(m) 返回 2
cap 只对切片和数组指针(如 *[N]T)及 chann
el 有效,返回底层数组可容纳的最大元素数(即从切片起始位置到数组末尾的长度)。
cap == len
s := make([]int, 3, 5) → len(s)=3, cap(s)=5
s2 := s[0:2] → len=2, cap=5(共享底层数组,容量不变)s3 := s[1:3] → len=2, cap=4(起始偏移后,剩余可用空间减少)append 接收一个切片和任意数量的同类型元素,返回一个新的切片。它可能复用原底层数组,也可能分配新数组(当容量不足时)。
s := []int{1,2}; s = append(s, 3) → [1 2 3]
s = append(s, 4, 5) → [1 2 3 4 5]
t := []int{6,7}; s = append(s, t...)(注意 ... 展开操作符)s := make([]int, 0, 2); s = append(s, 1,2,3) → 第三次追加会触发扩容,返回新底层数组实际开发中三者常配合使用:
result := make([]string, 0, len(src)),再循环 append(result, item)
sub := s[2:4] 后,len(sub)=2, cap(sub)=cap(s)-2