📜  如何在 Golang 中找到 Channel、Pointer、Slice、String 和 Map 的长度?

📅  最后修改于: 2021-10-24 13:25:01             🧑  作者: Mango

在 Golang 中, len函数用于查找通道、指针、切片、字符串和映射的长度。

通道:在 Go 语言中,通道是一个 goroutine 与另一个 goroutine 通信的媒介,并且这种通信是无锁的。

// Go program to illustrate
// how to find the length a channel
package main
    
import "fmt"
    
func main() {
  
    // Creating a channel using make() function
    ch:= make(chan int, 5)
    fmt.Printf("\nChannel: %d", len(ch))
    ch <- 0
    ch <- 1
    ch <- 2
    fmt.Printf("\nChannel: %d", len(ch))
}

输出:

Channel: 0
Channel: 3

指针: Go 编程语言或 Golang 中的指针是一个变量,用于存储另一个变量的内存地址。

// Go program to illustrate
// how to find the length a Pointer.
package main
  
import "fmt"
  
func main() {
  
    // Creating a pointer
    var poin *[10]string
    fmt.Printf("\nPointer: %d", len(poin))
}

输出:

Pointer: 10

Slice: Slice 是一个可变长度的序列,它存储类型相似的元素,不允许在同一个切片中存储不同类型的元素。

// Go program to illustrate
// how to find length Slice
package main
  
import "fmt"
  
func main() {
  
    // Creating a slice using make() function
    sliceEx := make([]int, 10)
    fmt.Printf("\nSlice: %d", len(sliceEx))
}

输出:

Slice: 10

字符串:它是一系列宽度可变的字符,其中每个字符都使用 UTF-8 编码由一个或多个字节表示。

// Go program to illustrate
// how to find length a String.
package main
  
import "fmt"
  
func main() {
    // Creating a string
    strEx := "India"
    fmt.Printf("\nString: %d", len(strEx))
}

输出:

String: 5

Map: Golang Maps 是一组无序的键值对的集合。

// Go program to illustrate
// how to find length a Map.
package main
    
import "fmt"
    
func main() {
  
    // Creating a map using make() function
    mapEx := make(map[string]int)
    mapEx["A"] = 10
    mapEx["B"] = 20
    mapEx["C"] = 30
    fmt.Printf("\nMap: %d", len(mapEx))
}

输出:

Map: 3