English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In the pointer, you can uselen()This function finds the length of the pointer. It is a built-in function that will return the total number of elements in the pointer to an array, even if the specified pointer is nil. This function is defined in the built-in.
Syntax:
func len(l Type) int
Here,lThe type is a pointer. Let's discuss this concept with the given example:
package main import ( "fmt" ) func main() { //Create and initialize //Pointer to an array //Using the var keyword var ptr1 [6]*int var ptr2 [3]*string var ptr3 [4]*float64 //Find the length //Pointer to an array //Using the len function fmt.Println("ptr1Length: ", len(ptr1)) fmt.Println("ptr2Length: ", len(ptr2)) fmt.Println("ptr3Length: ", len(ptr3)) }
Output:
ptr1Length: 6 ptr2Length: 3 ptr3Length: 4
Example of the length of a pointer to an array2:
//The length of a pointer to an array package main import ( "fmt" ) func main() { arr := [6]int{200, 300,400, 500, 600, 700} var x int //Create a pointer var p [4]*int //Allocate address for x = 0; x < len(p); x++ { p[x] = &arr[x] } //Display the result for x = 0; x < len(p); x++ { fmt.Printf(" p[%d] of ", x, d, " = ", d, *p[x]) } // Using the len() function to find the length fmt.Println("arr length: ", len(arr)) fmt.Println("p length: ", len(p)) }
Output:
p[0] of 200 p[1The value of 300 p[2The value of 400 p[3The value of 500 arr length: 6 p length: 4