×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang len() Function with Examples

Golang | len() Function: Here, we are going to learn about the built-in len() function with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 17, 2021 [Last updated : March 15, 2023]

len() Function

In the Go programming language, the len() is a built-in function that is used to get the length of the given parameter, according to its type:

  • Array: In the case of an array, it returns the number of elements.
  • Pointer to array: In the case of the pointer to an array, it returns the number of elements in *v (even if v is nil).
  • Slice, or map: In the case of a slice or a map, it returns the number of elements in v; if v is nil, len(v) is zero.
  • String: In the case of a string, it returns the number of bytes in v.
  • Channel: In the case of a channel, it returns the number of elements queued (unread) in the channel buffer;
  • if v is nil, len(v) is zero.

It accepts one parameter (v Type) and returns the length of it based on the type.

Syntax

func len(v Type) int

Parameter(s)

  • v : The value/variable whose length is to be found.

Return Value

The return type of the len() function is an int, it returns the length of the given parameter.

Example 1

// Golang program to demonstrate the
// example of len() function

package main

import (
	"fmt"
)

func main() {
	// Declaring & assigning some slices
	a := []int{10, 20, 30}
	b := []float32{20.23, 1.234, 10.20}
	c := []string{"Hello", "world"}

	// Printing their length
	fmt.Println("len(a):", len(a))
	fmt.Println("len(b):", len(b))
	fmt.Println("len(c):", len(c))
}

Output

len(a): 3
len(b): 3
len(c): 2

Example 2

// Golang program to demonstrate the
// example of len() function

package main

import (
	"fmt"
)

func main() {
	// Creating int and string slices
	s1 := []int{10, 20, 30}
	s2 := []string{"Hello", "World"}

	// Printing types and values of slices
	fmt.Printf("%T, %v\n", s1, s1)
	fmt.Printf("%T, %q\n", s2, s2)

	// Printing the Length
	fmt.Println("Length of s1:", len(s1))
	fmt.Println("Length of s2:", len(s2))

	// Appending some elements
	s1 = append(s1, 40, 50)
	s2 = append(s2, "How are you?", "Boys")

	// After appending,
	// Printing types and values of slices
	fmt.Println("After appending...")
	fmt.Printf("%T, %v\n", s1, s1)
	fmt.Printf("%T, %q\n", s2, s2)

	// Printing the Length
	fmt.Println("Length of s1:", len(s1))
	fmt.Println("Length of s2:", len(s2))
}

Output

[]int, [10 20 30]
[]string, ["Hello" "World"]
Length of s1: 3
Length of s2: 2
After appending...
[]int, [10 20 30 40 50]
[]string, ["Hello" "World" "How are you?" "Boys"]
Length of s1: 5
Length of s2: 4

Golang builtin Package »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.