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
The len
function takes a single mandatory parameter, v
, that can be a string
, array
, slice
, map
, or channel
.
The len
function returns one of the following, depending on the type of v
:
v
is an array, then the len
function returns the number of elements in v
.v
is a pointer to an array, then the len
function returns the number of elements at the location pointed to by v
, even if v
is nil
.v
is a slice
or map
, then the len
function returns the number of elements in v
. If v
is nil
, is returned.len
function returns the number of bytes in v
.len
function returns the number of queued elements in the buffer. If v
is nil
, is returned.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))}
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