How to find the Length of Channel, Pointer, Slice, String and Map in Golang?
In Golang, len function is used to find the length of a channel, pointer, slice, string, and map.
Channel: In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free.
// Go program to illustrate// how to find the length a channelpackage 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))} |
Output:
Channel: 0 Channel: 3
Pointer: Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable.
// 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))} |
Output:
Pointer: 10
Slice: Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.
// Go program to illustrate// how to find length Slicepackage main import "fmt" func main() { // Creating a slice using make() function sliceEx := make([]int, 10) fmt.Printf("\nSlice: %d", len(sliceEx))} |
Output:
Slice: 10
String: It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.
// 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))} |
Output:
String: 5
Map: Golang Maps is a collection of unordered pairs of key-value.
// 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))} |
Output:
Map: 3


