English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Error

Golang Miscellaneous

Go Language Pointer Capacity

In a pointer, you can usecap()Function to find the capacity of a pointer. This is a built-in function that returns the capacity of a pointer to an array. In Go language, capacity defines the maximum number of elements stored in a pointer to an array. This function is defined internally.

Syntax:

func cap(l Type) int

Here,lThe type is a pointer. Let's discuss this concept with an example:

// Go program to demonstrate how to find
//The capacity of the pointer to the array
package main
import (
    "fmt"
)
func main() {
    //Create and initialize
    //Pointing to an array
    //Using the var keyword
    var ptr1 [7]*int
    var ptr2 [5]*string
    var ptr3 [8]*float64
    //Find the capacity
    //Pointing to an array
    //Using cap() function
    fmt.Println("ptr1 Capacity: ", cap(ptr1))
    fmt.Println("ptr2 Capacity: ", cap(ptr2))
    fmt.Println("ptr3 Capacity: ", cap(ptr3))
}

Output:

ptr1 Capacity:  7
ptr2 Capacity:  5
ptr3 Capacity:  8

Example of Go getting the capacity of array pointers2:

package main
import (
    "fmt"
)
func main() {
    //Create an array
    arr := [8]int{200, 300, 400, 500, 600, 700, 100, 200}
    var x int
    //Create a pointer
    var p [5]*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("The value of p[%d] = %d\n", x, *p[x])
    }
    // Use the cap() function to find the capacity
    fmt.Println("The capacity of arr: ", cap(arr))
    fmt.Println("The capacity of p: ", cap(p))
}

Output:

p[0] The value of = 200
p[1The value of = 300
p[2The value of = 400
p[3The value of = 500
p[4The value of = 600
The capacity of arr:  8
The capacity of p:  5