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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
}
chevron_right

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
}
chevron_right

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
}
chevron_right

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
}
chevron_right

Output:

String: 5

Map: Golang Maps is a collection of unordered pairs of key-value.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
}
chevron_right

Output:

Map: 3




Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :