golang len()
时间: 2023-10-12 19:59:49 浏览: 45
len() 函数是用来获取字符串、数组、切片、字典或通道等数据结构的长度的。在 Golang 中,len() 函数的用法如下:
1. 字符串长度:
```go
str := "Hello, World!"
length := len(str)
fmt.Println(length) // 输出:13
```
2. 数组长度:
```go
arr := [5]int{1, 2, 3, 4, 5}
length := len(arr)
fmt.Println(length) // 输出:5
```
3. 切片长度:
```go
slice := []int{1, 2, 3, 4, 5}
length := len(slice)
fmt.Println(length) // 输出:5
```
4. 字典长度:
```go
dict := map[string]int{"apple": 1, "banana": 2, "cherry": 3}
length := len(dict)
fmt.Println(length) // 输出:3
```
5. 通道长度(缓冲区中剩余未被读取的元素个数):
```go
ch := make(chan int, 3)
ch <- 1
ch <- 2
ch <- 3
length := len(ch)
fmt.Println(length) // 输出:3
```
需要注意的是,len() 函数返回的是数据结构中元素的个数,而不是索引的最大值。