How to find the Length of Channel, Pointer, Slice, String and Map in Golang?
Last Updated :
10 May, 2020
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.
package main
import "fmt"
func main() {
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.
package main
import "fmt"
func main() {
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.
package main
import "fmt"
func main() {
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.
package main
import "fmt"
func main() {
strEx := "India"
fmt.Printf("\nString: %d", len(strEx))
}
|
Output:
String: 5
Map: Golang Maps is a collection of unordered pairs of key-value.
package main
import "fmt"
func main() {
mapEx := make(map[string]int)
mapEx["A"] = 10
mapEx["B"] = 20
mapEx["C"] = 30
fmt.Printf("\nMap: %d", len(mapEx))
}
|
Output:
Map: 3