Golang 如何找到通道、指针和切片的容量
在Go语言中,容量定义了一个特定数据类型可以保存的最大元素数。在本文中,我们的任务是找到Golang中通道、指针和切片的容量,可以使用 cap() 函数。
语法:
func cap(l Type) int
这里,l的类型是指针。
让我们通过以下示例来讨论这个概念:
示例1: 在此示例中,使用cap()函数查找Golang中指针的容量。
// Go program to illustrate how to find the
// capacity of the pointer
package main
import (
"fmt"
)
// Main function
func main() {
// Creating and initializing
// pointer
// Using var keyword
var ptr1 [7]*int
var ptr2 [5]*string
var ptr3 [8]*float64
// Finding the capacity of
// the pointer
// Using cap function
fmt.Println("Capacity of ptr1: ", cap(ptr1))
fmt.Println("Capacity of ptr2: ", cap(ptr2))
fmt.Println("Capacity of ptr3: ", cap(ptr3))
}
输出:
Capacity of ptr1: 7
Capacity of ptr2: 5
Capacity of ptr3: 8
示例2: 在此示例中,使用cap()函数查找Golang中通道的容量。
// Go program to illustrate how to find the
// capacity of the Channel
package main
import (
"fmt"
)
// Main function
func main() {
// Creating and initializing
// Channel
// Using var keyword
ch1 := make(chan int, 7)
ch2 := make(chan string, 5)
ch3 := make(chan float64, 8)
// Finding the capacity of
// the Channel
// Using cap function
fmt.Println("Capacity of Channel1: ", cap(ch1))
fmt.Println("Capacity of Channel2: ", cap(ch2))
fmt.Println("Capacity of Channel3: ", cap(ch3))
}
输出:
Capacity of Channel1: 7
Capacity of Channel2: 5
Capacity of Channel3: 8
示例3: 在此示例中,使用cap()函数查找Golang中切片的容量。
// Go program to illustrate how to find the
// capacity of the Slice
package main
import (
"fmt"
)
// Main function
func main() {
// Creating and initializing
// Slice
// Using var keyword
sl1 := make([]int, 0, 7)
sl2 := make([]string, 0, 5)
sl3 := make([]float64, 0, 8)
// Finding the capacity of
// the Slice
// Using cap function
fmt.Println("Capacity of Slice1: ", cap(sl1))
fmt.Println("Capacity of Slice2: ", cap(sl2))
fmt.Println("Capacity of Slice3: ", cap(sl3))
}
输出:
Capacity of Slice1: 7
Capacity of Slice2: 5
Capacity of Slice3: 8