How to find the length of the pointer in Golang?

Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang are also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.).
In pointers, you are allowed to find the length of the pointer with the help of len() function. This function is a built-in function returns the total number of elements present in the pointer to an array, even if the specified pointer is nil. This function is defined under builtin.

Syntax:

func len(l Type) int

Here, the type of l is a pointer. Let us discuss this concept with the help of given examples:



Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to find the
// length of the pointer to an array
package main
  
import (
    "fmt"
)
  
// Main function
func main() {
  
    // Creating and initializing
    // pointer to array
    // Using var keyword
    var ptr1 [6]*int
    var ptr2 [3]*string
    var ptr3 [4]*float64
  
    // Finding the length of 
    // the pointer to array
    // Using len function
    fmt.Println("Length of ptr1: ", len(ptr1))
    fmt.Println("Length of ptr2: ", len(ptr2))
    fmt.Println("Length of ptr3: ", len(ptr3))
  
}

chevron_right


Output:

Length of ptr1:  6
Length of ptr2:  3
Length of ptr3:  4

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to find
// the length of the pointer to an array
package main
  
import (
    "fmt"
)
  
// Main function
func main() {
  
    // Creating an array
    arr := [6]int{200, 300,
        400, 500, 600, 700}
      
    var x int
  
    // Creating pointer
    var p [4]*int
  
    // Assigning the address
    for x = 0; x < len(p); x++ {
      
        p[x] = &arr[x]
    }
  
    // Displaying result
    for x = 0; x < len(p); x++ {
      
        fmt.Printf("Value of p[%d] = %d\n", x, *p[x])
    }
  
    // Finding length
    // Using len() function
    fmt.Println("Length of arr: ", len(arr))
    fmt.Println("Length of p: ", len(p))
}

chevron_right


Output:

Value of p[0] = 200
Value of p[1] = 300
Value of p[2] = 400
Value of p[3] = 500
Length of arr:  6
Length of p:  4


My Personal Notes arrow_drop_up

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 :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.