What is the len function in Golang?
The len function in Golang is a built-in function that returns the length of a provided parameter, depending on the parameter’s type.
The prototype of the len function is shown below:
func len(v Type) int
Parameters
The len function takes a single mandatory parameter, v, that can be a string, array, slice, map, or channel.
Return value
The len function returns one of the following, depending on the type of v:
- Array: If
vis an array, then thelenfunction returns the number of elements inv. - Pointer to an array: If
vis a pointer to an array, then thelenfunction returns the number of elements at the location pointed to byv, even ifvisnil. - Slice, or map: If
vis asliceormap, then thelenfunction returns the number of elements inv. Ifvisnil, is returned. - String: The
lenfunction returns the number of bytes inv. - Channel: The
lenfunction returns the number of queued elements in the buffer. Ifvisnil, is returned.
Code
The code below shows how the len function works in Golang:
package mainimport ("fmt")func main() {//initializing variablesa := "Hello World"b := [6]int{2, 3, 5, 7, 11, 13}var c []int//computing lengthsa_length := len(a)b_length := len(b)//printing resultsfmt.Println("The length of a is: ", a_length)fmt.Println("The length of b is: ", b_length)fmt.Println("The length of c is: ", len(c))}
Explanation
First, the code initializes a string (a), an array (b) that contains elements, and an empty slice (c).
The len function proceeds to compute the length of each of these variables and outputs the results accordingly.
Since a is a string, the len function returns the number of characters it contains, i.e., . Similarly, as b is an array, the len function returns the number of elements it contains, i.e., . Finally, since c is a nil slice, the len function returns .
Free Resources